Passing selected rows in Gridview to another Page in Gridview dynamically - Part 2

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

This article we explain how we can pass the selected rows of the grid view to next page and bind it to the grid view on Second Page

Introduction


In the previous article of

 Pass Selected Rows of Grid View to another Grid View Dynamically we saw that we can get selected records of grid view and bind it to another grid view. But there can be a requirement where we need to bind selected records of The Grid View of Page 1 to the Grid View of Page 2.


This is the Extension of the previous article of 

Pass Selected Rows of Grid View to another Grid View Dynamically


Objective

  1. Passing the Selected Records of the Grid View to another Page and Bind it to the Grid View of another page.

Using the code


  1. We have already created a Website in the previous article.So Over here we will add a New Web form and drag and drop a Grid View and Add a data Column Named Country.
  2. Now we will go to the Previous Page i.e. Page 1 and make changes to the code on the button click event of Pass Selected Records Button.

Lets Start Implementation

// Tables and Stored Procedure
USE [DNF]
GO

/****** Object:  Table [dbo].[Countries]    Script Date: 07/22/2013 22:41:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Countries](
	[CountryID] [int] IDENTITY(1,1) NOT NULL,
	[Countries] [varchar](25) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO																								-- Proc for getting Countries			
create proc [dbo].[GetCountriesList]
as
begin
select * from Countries
end
GO

HTML Mark Up for Page 1
<%@ 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 
        Page - Part 2</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>
    </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);
                    
                }
            }
      
        }
        // Adding the Data table to Session for passing it to another page.
        Session.Add("dtgetselectedRecords", dtgetselectedRecords);
        Server.Transfer("~/Page2.aspx");
        

    }
}
// Page 2 HTML Mark Up 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page2.aspx.cs" Inherits="Page2" %>

<!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" align="center">
    Getting Selected Rows from Previous Page to this page
        using Session Object
    </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>
    </form>
</body>
</html>
// Code Behind of Page 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Page2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {	// Over here we fetch the datatable from session i.e. stored in previous page and 		//passed here 
            DataTable dtselectedRows = Session["dtgetselectedRecords"] as DataTable;
            xSelected.DataSource = dtselectedRows;
            xSelected.DataBind();
        }
    }
}

Explanation of the Pass Selected Records

  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. Then we use Session.Add Property to add the data table and redirect the page to page2
  7.  Now on Page2 on the Page Load event we fetch the data table from Session and assign to the Data grid as its Source and Bind it.

Output 1 : Selecting the Records




Output 2 : Passing the Selected Record to Page 2







Conclusion


I owe thanks to the Moderator of Articles Section for giving an Idea to extend my article to Second Part.



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: Charan44 on: 12/25/2016 | Points: 25
Dear sir ,

i have two colums, Name and county i want to display this both selected columns to next page using session but the result is displaying in only one columns please correct this code




protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();


}
}
protected void Button1_Click(object sender, EventArgs e)
{
//transfer to another page
DataTable dtgetselectedrecords = new DataTable();



dtgetselectedrecords.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });


foreach (GridViewRow gvrow in GridView1.Rows)
{

if(gvrow.RowType==DataControlRowType.DataRow)
{

CheckBox chkSelect = (gvrow.Cells[0].FindControl("chkSelect") as CheckBox);

if (chkSelect.Checked)
{

string Name = gvrow.Cells[1].Text;

string Country=gvrow.Cells[2].Text;
dtgetselectedrecords.Rows.Add(Name);
dtgetselectedrecords.Rows.Add(Country);

}


}




}
Session.Add("dtgetselectedrecords", dtgetselectedrecords);
Server.Transfer("~/Retrieve.aspx");
}


private void BindGrid()
{
try
{

string constr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string query = "select * from Customers";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{

}


}


Login to post response

Comment using Facebook(Author doesn't get notification)