In this article we will be checking how we can pass selected rows in Gridview to another Gridview dynamically.
For Selecting the Rows we will be using Checkbox
Introduction
Hello Friends,
Some time back working with Grid Views we were given a task at user level where we needed to select Custom Rows and pass it to another Gridview Rows.
The reason for this when you heavy data in Grid Views and you want to show custom data according to user this can be useful.
Objective
- Adding Check-box to Grid-view
- Getting the Rows of checked Grid-views and passing it to another Grid
Using the code
- Create a New Empty Website in VS 2010
- Add a GridView to the web form and add a Column with header as Countries and add an Template Field with Header Select
- Now go to Edit Templates View and drag and Drop a Check Box in the Item Template.
- To Add Check Box to Item Template (Check Screen 1).
- Now we will add a Button and another Grid View and assign the Column with Header Countries and and DataColumn Countries too.
Output Screen 1 :
Lets Start Implementation
// Tables and Stored Procedures
USE [DNF]
GO
/****** Object: Table [dbo].[Countries] Script Date: 07/22/2013 20:08:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
-- Table for Countries
CREATE TABLE [dbo].[Countries](
[CountryID] [int] IDENTITY(1,1) NOT NULL,
[Countries] [varchar](25) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
-- Stored Proc for Countries List
USE [DNF]
GO
/****** Object: StoredProcedure [dbo].[GetCountriesList] Script Date: 07/22/2013 20:08:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[GetCountriesList]
as
begin
select * from Countries
end
GO
//HTML Mark up
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PassingGridViewSample.aspx.cs"
Inherits="PassingGridViewSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
font-family: "Trebuchet MS";
font-size: x-large;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style1" style="text-align: center">
Selecting Grid View Rows and Passing it to another Grid View</div>
<br />
<br />
<div align="center">
<asp:GridView ID="xdata" runat="server" HeaderStyle-BackColor="Bisque" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Countries" HeaderText="Countries" />
</Columns>
</asp:GridView>
</div>
<br />
<br />
<div align="center">
<asp:Button ID="btnGetSelectedRecords" runat="server"
Text="Pass Selected Records to Grid View"
onclick="btnGetSelectedRecords_Click" />
</div>
<br />
<br />
<div align="center">
<asp:GridView ID="xSelected" runat="server" HeaderStyle-BackColor="Chartreuse" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Countries" HeaderText="Countries" />
</Columns>
</asp:GridView>
</div>
<br />
<br />
<div>
</div>
</form>
</body>
</html>
// Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class PassingGridViewSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
try
{
// Function to bind the data to Grid.
SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
con.Open();
SqlCommand getcontent = new SqlCommand("GetCountriesList", con);
getcontent.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(getcontent);
DataSet ds = new DataSet();
da.Fill(ds);
xdata.DataSource = ds;
xdata.DataBind();
}
catch (Exception ex)
{
}
}
protected void btnGetSelectedRecords_Click(object sender, EventArgs e)
{
// creation of data table
DataTable dtgetselectedRecords = new DataTable();
// Adding Dynamic Column to the datatable using the add range method
dtgetselectedRecords.Columns.AddRange(new DataColumn[1] {new DataColumn("Countries")});
// Running a For Loop accross the First Grid View
foreach (GridViewRow gvrow in xdata.Rows)
{
if (gvrow.RowType == DataControlRowType.DataRow)
{
//Finding the Checkbox in the Gridview
CheckBox chkSelect = (gvrow.Cells[0].FindControl("chkSelect") as CheckBox);
// Checking which checkbox are selected
if (chkSelect.Checked)
{
// assigning the records to a string to the cells
string Countries = gvrow.Cells[1].Text;
// Adding the Rows to the datatable
dtgetselectedRecords.Rows.Add(Countries);
}
}
}
// Assigning the data source as data table that we have genereated
xSelected.DataSource = dtgetselectedRecords;
xSelected.DataBind();
}
}
Explanation of GetSelectedRecords Click Event
- First we will create a data table
- Then we add data columns to the data table using add column range method and specify the name of the column
- Now we will run a For Loop through all the rows in the First Grid and find the check box control in the first grid using findcontrol method.
- Once we find the check box we will check the which check box are selected and add the cells to a string variable
- Finally we add the row to the datatable using add row method.
- We then Bind the Second Data Grid
Output 2 : Selecting the Records
Output 3 : Passed the Selected Rows to another Grid View
Conclusion
This can be useful also if you want to send selected records to another page using Session Object.