Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to pass multiple selected values of a GridView to another page in ASP.NET

Author: Alanna Kremer
Download Source Code : 1368_PassGridViewValuesToAnotherPage.zip

Sometimes you may need to pass multiple selected values of a GridView from one page to another in ASP.NET. This article will show how we can achieve this task.

 

You can pass values between pages using different techniques. Query String is used to pass values to another page when we have a small number of values because browsers allow limited number of characters in URL. We can use session state when we have lots of values to pass to another page. Session variable can store DataTable to pass between pages.

When we select a row of data bound GridView, we can have multiple values from a single row. Many times you need to select more than one row so values could be in hundreds. You can use session state to pass these values to another page or you can get these values by using PreviousPage property of the Page where you want to retrieve these values. I will show both of these techniques to pass multiple values to another page in my article.
 
 
  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual C# or Visual Basic > ASP.NET Empty Web Site > Click Ok
  4. Website > Add New Item > Web Form > Click Add
  5. Again Website > Add New Item > Web Form > Click Add
  6. Drag and Drop a SqlDataSource, a GridView, two Buttons and a Label in Default.aspx page
  7. Use SQLDataSource to get data from database. I have used “Products” table of NORTHWIND database. Code in Default.aspx page will look like below.

    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
            SelectCommand="SELECT [ProductID], [ProductName], [CategoryID], [UnitPrice] FROM [Products]"></asp:SqlDataSource>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                AutoGenerateColumns="False" DataKeyNames="ProductID"
                DataSourceID="SqlDataSource1">
            <Columns>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
            </ItemTemplate>
            </asp:TemplateField>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID"
                    InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName"
                    SortExpression="ProductName" />
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
                    SortExpression="CategoryID" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
                    SortExpression="UnitPrice" />
            </Columns>
        </asp:GridView>
       
    <br />
    <asp:Button ID="Button1" runat="server" Text="Pass Selected Products"
       onclick="Button1_Click" />   
    <br />
    <asp:Button ID="Button2" runat="server" Text="Pass Selected Products"
       onclick="Button2_Click" />   
    <br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
     
  8. Write code below in Button1 click event

    C#
     
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)gvRow.Cells[0].FindControl("CheckBox1");
            if (checkbox.Checked)
            {
                Server.Transfer("~/Default2.aspx");
            }
            else
            {
                Label1.Text = "Please select a product to pass to another page";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
     
    VB.NET
     
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim checkbox As CheckBox = DirectCast(gvRow.Cells(0).FindControl("CheckBox1"), CheckBox)
            If checkbox.Checked Then
                Server.Transfer("~/Default2.aspx")
            Else
                Label1.Text = "Please select a product to pass to another page"
                Label1.ForeColor = System.Drawing.Color.Red
            End If
        Next
    End Sub
     
    I have used a Foreach loop to iterate through GridView rows and get the CheckBox control from the first cell of GridView. If CheckBox is checked you can transfer to Default.aspx page. Note here, I have used Server.Transfer() instead of Response.Redirect because you can get values on another page using PreviousPage property when you have used Server.Transfer() but you cannot do this in by using Response.Redirect().
     
  9. Now write code below in Button2 click event

    C#
     
    protected void Button2_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
     
        dt.Columns.Add("ProductID", typeof(int));
        dt.Columns.Add("ProductName", typeof(string));
        dt.Columns.Add("CategoryID", typeof(int));
        dt.Columns.Add("UnitPrice", typeof(decimal));
     
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)gvRow.Cells[0].FindControl("CheckBox1");
            if (checkbox.Checked)
            {
                DataRow row = dt.NewRow();
                row["ProductID"] = gvRow.Cells[1].Text;
                row["ProductName"] = gvRow.Cells[2].Text;
                row["CategoryID"] = gvRow.Cells[3].Text;
                row["UnitPrice"] = gvRow.Cells[4].Text;
                dt.Rows.Add(row);
            }
        }
        Session["ProductsTable"] = dt;
        Response.Redirect("~/Default2.aspx");
    }
     
    VB.NET
     
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
        Dim dt As New DataTable()
        dt.Columns.Add("ProductID", GetType(Integer))
        dt.Columns.Add("ProductName", GetType(String))
        dt.Columns.Add("CategoryID", GetType(Integer))
        dt.Columns.Add("UnitPrice", GetType(Decimal))
     
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim checkbox As CheckBox = DirectCast(gvRow.Cells(0).FindControl("CheckBox1"), CheckBox)
            If checkbox.Checked Then
                Dim row As DataRow = dt.NewRow()
                row("ProductID") = gvRow.Cells(1).Text
                row("ProductName") = gvRow.Cells(2).Text
                row("CategoryID") = gvRow.Cells(3).Text
                row("UnitPrice") = gvRow.Cells(4).Text
                dt.Rows.Add(row)
            End If
        Next
        Session("ProductsTable") = dt
        Response.Redirect("~/Default2.aspx")
    End Sub
     
    I have created a DataTable dynamically to add and store values in Session state. I have added four columns to DataTable. I have used foreach loop to iterate through GridView and find CheckBox control. When CheckBox is checked, I have created a DataRow, added GridView cell values of this row and added the row to DataTable. I have assigned DataTable to Session variable and redirect the page to Default.aspx. Here I have used Response.Redirect() instead of Server.Transfer() because I am storing values in Session.
     
  10. Add a label and a GridView in Default2.aspx page. Code will look like below.

    <asp:Label ID="Label1" runat="server" ></asp:Label>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
     
  11. Write code below in Page Load event to retrieve values from previous page

    C#
     
    if (Page.PreviousPage != null)
    {
        GridView GridView1 = (GridView)Page.PreviousPage.FindControl("GridView1");
     
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)gvRow.Cells[0].FindControl("CheckBox1");
            if (checkbox.Checked)
            {
                Label1.Text += "ProductID: " + gvRow.Cells[0].Text + "<br />";
                Label1.Text += "ProductName: " + gvRow.Cells[1].Text + <br />";
                Label1.Text += "CategoryID: " + gvRow.Cells[2].Text + "<br />";
                Label1.Text += "UnitPrice: " + gvRow.Cells[3].Text + "<br />";
             }
        }
    }
     
    VB.NET
     
    If Page.PreviousPage IsNot Nothing Then
        Dim GridView1 As GridView = DirectCast(Page.PreviousPage.FindControl("GridView1"), GridView)
     
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim checkbox As CheckBox = DirectCast(gvRow.Cells(0).FindControl("CheckBox1"), CheckBox)
            If checkbox.Checked Then
                Label1.Text += "ProductID: " + gvRow.Cells(0).Text + "<br />"
                Label1.Text += "ProductName: " + gvRow.Cells(1).Text + "<br />"
                Label1.Text += "CategoryID: " + gvRow.Cells(2).Text + "<br />"
                Label1.Text += "UnitPrice: " + gvRow.Cells(3).Text + "<br />"
            End If
        Next
    End If
     
    I have checked PreviousPage property of this Page. If it is not null then I have found the GridView control of the previous page and iterate through the GridView rows. I have found CheckBox control, if the CheckBox is checked then I have retrieved the values and displayed on a Label.
     
  12. Now write code below in page Load event to retrieve values using session state

    C#
     
    if (Session["ProductsTable"] != null)
    {
        DataTable dt = (DataTable)Session["ProductsTable"];
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Session["ProductsTable"] = null;
    }
     
    VB.NET
     
    If Session("ProductsTable") IsNot Nothing Then
        Dim dt As DataTable = CType(Session("ProductsTable"), DataTable)
        GridView1.DataSource = dt
        GridView1.DataBind()
        Session("ProductsTable") = Nothing
    End If
     
    I have checked the Session variable here. If it is not null then I have retrieved the DataTable from session and displayed it on a GridView.
     
  13. Set Default.aspx as start page and press F5 

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to add Meta tags programmatically in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net