Skip to main content

Move Selected Gridview Rows to Another Gridview in Asp.net

Introduction


Here I will explain how to move or transfer selected checkbox gridview rows to another gridview in asp.net using c#, vb.net or copy one gridview row to another gridview in asp.net using c#, vb.net.

Description

In previous posts I explained Display images in gridview from database in asp.net, Enable/Disable checkbox in gridview based on condition, 
asp.net gridview examples and bind data to textbox control in gridviewBind data to dropdownlist  in gridview and many articles relating to asp.net, c#, vb.net, c#,vb.net. Now I will explain how to move selected rows from one gridview to another gridview in asp.netusing c#, vb.net.

To implement this first we need to write the code in aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tranfer selected gridview rows to another gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"OnCheckedChanged="chkSelect_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<br />
<b>Second Gridview Data</b>
<asp:GridView ID="gvTranferRows" AutoGenerateColumns="false" CellPadding="5" runat="server"EmptyDataText="No Records Found">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>

Now add following namespaces in codebehind

C# Code

using System;
using System.Data;
using System.Web.UI.WebControls;

After that add following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
BindSecondGrid();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId"typeof(Int32));
dt.Columns.Add("UserName"typeof(string));
dt.Columns.Add("Education"typeof(string));
dt.Columns.Add("Location"typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void chkSelect_CheckChanged(object sender, EventArgs e)
{
GetSelectedRows();
BindSecondGrid();
}
protected void BindSecondGrid()
{
DataTable dt = (DataTable)ViewState["GetRecords"];
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
private void GetSelectedRows()
{
DataTable dt;
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
else
dt = CreateTable();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvDetails.Rows[i].Cells[0].FindControl("chkSelect");
if (chk.Checked)
{
dt = AddGridRow(gvDetails.Rows[i], dt);
}
else
{
dt = RemoveRow(gvDetails.Rows[i], dt);
}
}
ViewState["GetRecords"] = dt;
}
private DataTable CreateTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId");
dt.Columns.Add("UserName");
dt.Columns.Add("Education");
dt.Columns.Add("Location");
dt.AcceptChanges();
return dt;
}
private DataTable AddGridRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("UserId = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
int rowscount = dt.Rows.Count - 1;
dt.Rows[rowscount]["UserId"] = gvRow.Cells[1].Text;
dt.Rows[rowscount]["UserName"] = gvRow.Cells[2].Text;
dt.Rows[rowscount]["Education"] = gvRow.Cells[3].Text;
dt.Rows[rowscount]["Location"] = gvRow.Cells[4].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("UserId = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}

VB.NET Code


Imports System.Data
Imports System.Web.UI.WebControls
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
BindSecondGrid()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId"GetType(Int32))
dt.Columns.Add("UserName"GetType(String))
dt.Columns.Add("Education"GetType(String))
dt.Columns.Add("Location"GetType(String))
Dim dtrow As DataRow = dt.NewRow()
' Create New Row
dtrow("UserId") = 1
'Bind Data to Columns
dtrow("UserName") = "SureshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Chennai"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 2
'Bind Data to Columns
dtrow("UserName") = "MadhavSai"
dtrow("Education") = "MBA"
dtrow("Location") = "Nagpur"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 3
'Bind Data to Columns
dtrow("UserName") = "MaheshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Nuzividu"
dt.Rows.Add(dtrow)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Protected Sub chkSelect_CheckChanged(ByVal sender As ObjectByVal e As EventArgs)
GetSelectedRows()
BindSecondGrid()
End Sub
Protected Sub BindSecondGrid()
Dim dt As DataTable = DirectCast(ViewState("GetRecords"), DataTable)
gvTranferRows.DataSource = dt
gvTranferRows.DataBind()
End Sub
Private Sub GetSelectedRows()
Dim dt As DataTable
If ViewState("GetRecords"IsNot Nothing Then
dt = DirectCast(ViewState("GetRecords"), DataTable)
Else
dt = CreateTable()
End If
For i As Integer = 0 To gvDetails.Rows.Count - 1
Dim chk As CheckBox = DirectCast(gvDetails.Rows(i).Cells(0).FindControl("chkSelect"), CheckBox)
If chk.Checked Then
dt = AddGridRow(gvDetails.Rows(i), dt)
Else
dt = RemoveRow(gvDetails.Rows(i), dt)
End If
Next
ViewState("GetRecords") = dt
End Sub
Private Function CreateTable() As DataTable
Dim dt As New DataTable()
dt.Columns.Add("UserId")
dt.Columns.Add("UserName")
dt.Columns.Add("Education")
dt.Columns.Add("Location")
dt.AcceptChanges()
Return dt
End Function
Private Function AddGridRow(ByVal gvRow As GridViewRow, ByVal dt As DataTable) As DataTable
Dim dr As DataRow() = dt.[Select]("UserId = '" & gvRow.Cells(1).Text & "'")
If dr.Length <= 0 Then
dt.Rows.Add()
Dim rowscount As Integer = dt.Rows.Count - 1
dt.Rows(rowscount)("UserId") = gvRow.Cells(1).Text
dt.Rows(rowscount)("UserName") = gvRow.Cells(2).Text
dt.Rows(rowscount)("Education") = gvRow.Cells(3).Text
dt.Rows(rowscount)("Location") = gvRow.Cells(4).Text
dt.AcceptChanges()
End If
Return dt
End Function
Private Function RemoveRow(ByVal gvRow As GridViewRow, ByVal dt As DataTable) As DataTable
Dim dr As DataRow() = dt.[Select]("UserId = '" & gvRow.Cells(1).Text & "'")
If dr.Length > 0 Then
dt.Rows.Remove(dr(0))
dt.AcceptChanges()
End If
Return dt
End Function
End Class



Comments

Popular posts from this blog

.NET Core API With Dapper, Repository And UnitOfWork

  Introduction In this tutorial, you will use ASP.NET Core Web API to create a web API that returns a list of brands. This article focuses on creating web API using dapper, repository pattern, and UnitOfWork pattern in .NET 8. I will guide you through the steps by step to create web API. HTTP is not just for serving up web pages. HTTP is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications. ASP.NET Core Web API is a framework for building web APIs on top of the .NET Framework. Creating a New Project in Visual Studio Launch Visual Studio and select Create a New Project. Creating a Core Web API Start Visual Studio and choose Create a new project. In the Create a new project dialog, select ASP.NET Core Web API Click Next. Configuring You...

.Net framework interview questions

What is the .NET Framework? The .NET Framework is a set of technologies that form an integral part of the .NET Platform. It is Microsoft’s managed code programming model for building applications. The .NET Framework has two main components: Common Language Runtime (CLR): The CLR is one of the foundation in the .NET framework and provides a common set of services for applications developed on Microsoft .Net Technologies. .NET Framework class library: The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality. What is CTS (Common Type System)? The common type system (CTS) defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime’s support for cross-language integration. The common type system performs the following functions: ·          Establishes a framework that...