Pass Selected Rows of Grid View to another Grid View Dynamically - Part 1

Raj.Trivedi
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 24739 red flag

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


  1. Adding Check-box to Grid-view
  2. Getting the Rows of checked Grid-views and passing it to another Grid

Using the code


  1. Create a New Empty Website in VS 2010
  2. Add a GridView to the web form and add a Column with header as Countries and add an Template Field with Header Select
  3. Now go to Edit Templates View and drag and Drop a Check Box in the Item Template.
  4. To Add Check Box to Item Template (Check Screen 1).
  5. 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

  1. First we will create a data table
  2. Then we add data columns to the data table using add column range method and specify the name of the column
  3. 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.
  4. Once we find the check box we will check the which check box are selected and add the cells to a string variable
  5. Finally we add the row to the datatable using add row method.
  6. 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.



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Posted by: Prabhakar on: 7/27/2013 | Points: 25
Super Article . . nice one

Login to post response

Comment using Facebook(Author doesn't get notification)