Thursday, November 10, 2011

Using ASP.NET and jQuery to Pass Multiple Values from a GridView to Another Page


In one of our previous article Pass Multiple Values from a GridView to Another Page using ASP.NET, we had seen how to select a GridView row and pass multiple values of the selected row to another page. We had made use of the 'DataNavigateUrlFields' to set the names of the fields and construct the URL in the HyperLinkField.
In this article, we will simplify the approach using jQuery and pass values without the need of a Hyperlink field. If you are new to jQuery, I would strongly suggest you to check this: Using jQuery with ASP.NET - A Beginner's Guide
Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-1.2.6-vsdoc.js) > Select the files and click Add.
Now drag and drop the jquery-1.2.6.js file from the Solution Explorer to the <head> section of your page to create a reference as shown below:
<head runat="server">
    <title></title>
    <script src="Script/jquery-1.2.6.js" type="text/javascript"></script>
   
Now drag and drop a SqlDataSource Control to the Default.aspx page and use the wizard to connect to the Northwind database. Select the CustomerId, CompanyName, ContactName, Address and City from the Customers table. The wizard will also prompt you to save the connection string in the web.config file. Choose to do so. The design code will look similar to the following:
           <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
            </asp:SqlDataSource>
An entry will be added to the web.config file as shown below:
 <connectionStrings>
    <add name="NorthwindConnectionString"
         connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
 </connectionStrings>
Now add a GridView control to the page and using the smart tag, select the DataSource to be SqlDataSource1 in the GridView tasks panel. Using the same panel, click on the Enable Paging and Enable Sorting checkboxes. The source will look similar to the following. Observe that the DataKeyNames is set to ‘CustomerId’, that is the primary key of the Customers table
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
            <Columns>                          
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            </Columns>
        </asp:GridView>
We will now add another page in our project. In the Solution Explorer, right click the project > Add New Item > Web Form > Rename it to ‘CustomerDetails.aspx’. In the Page_Load of CustomerDetails.aspx, add the following code to retrieve the query string variables from the URL:
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        string cid = Request.QueryString["CID"];
        string cname = Request.QueryString["CName"];
        Response.Write("CustomerID= " + cid + " : " + "CompanyName= " + cname);
    }
VB.NET
      Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)
            Dim cid As String = Request.QueryString("CID")
            Dim cname As String = Request.QueryString("CName")
            Response.Write("CustomerID= " & cid & " : " & "CompanyName= " & cname)
      End Sub
Time to see some jQuery magic. Go back the Default.aspx and add the following jQuery code in the <head>:
    <script type="text/javascript">
 
        $(document).ready(function() {
            $("tr").click(function(event) {
                var row = jQuery(this)
                var firstParam = row.children("td:eq(0)").text();
                var secondParam = row.children("td:eq(1)").text();               
                var navUrl = "http://localhost:7250/GridViewRowJQuery/CustomerDetails.aspx?cid=" + firstParam + "&cname=" + secondParam;
                top.location = navUrl;
 
            });
        });
    </script>
The code handles the click event on a table row and extracts the first and second column value for that row. The url is then formed using the two parameters and passed to the CustomerDetails.aspx page. That’s it. Run the code and on click of every row of the GridView, the CustomerId and CustomerName are passed to the next page. Simple!
I hope this article was useful and I thank you for viewing it. The entire source code of the article can be downloaded from here