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

Posted by: Suprotim Agarwal , on 12/24/2008, in Category jQuery and ASP.NET
Views: 78290
Abstract: In this article, we will see how to use ASP.NET and jQuery to pass multiple values of a GridView row to another page.
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 Object, ByVal 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

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Danny117 on Friday, February 13, 2009 5:40 PM
I've never used "jQuery(this)" but I'm going to try.
jquery(this) is definately more readable than this or $(this).

Although I do have lots of working javascript without semicolons that somehow works.
Comment posted by Thiago on Friday, February 13, 2009 9:01 PM
I think you should use $(element) instead of jquery(element) to keep your script files smaller. once you publish your stuff online, it's not about being readable, but functional.
Comment posted by Suprotim Agarwal on Saturday, February 14, 2009 10:13 PM
I second Thiago on that!
Comment posted by Markive on Monday, February 16, 2009 7:09 AM
The problem with: $(element) is that it can conflict with other libraries, jQuery(this) is therefore safer..
Comment posted by Suprotim Agarwal on Monday, February 16, 2009 7:25 AM
Markive: jQuery is well written and has a simple solution for library conflicts
Just use jQuery.noConflict(); and it will take care of the rest.

More info over here: http://docs.jquery.com/Core/jQuery.noConflict
Comment posted by Burak Sarica on Monday, February 23, 2009 7:45 AM
Hi Suportim,
noConflict disables the $() and forces developer to use jQuery instead. So this is nothing further from Markive words?
Comment posted by Naveed on Tuesday, February 24, 2009 5:03 AM
Its nice work I've seen an example here which pass multiple values to function in c# via jquery
http://www.isolutionteam.co.uk/json-jquery-ajax-aspnet-and-c-to-get-ajaxed-data-table-rows-passing-multiple-parameters/
Comment posted by Vittal on Saturday, March 14, 2009 1:33 PM
What if there are more than one one grid view on display in the page. How would you go about distinguishing between them?
Comment posted by Waseem on Thursday, April 30, 2009 6:06 AM
I have re-written your jquery
this is an alternative if you prefer using $(function() {...}
and do not want to use the obj.children() function

=========== Original jquery ================
        $(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;

            });
        });

============== New Jquery ================
        $(function() {
            $("tr").click(function(event) {
                var row = $(this);
                var firstParam = $("td", row).eq(0).text();
                var secondParam = $("td", row).eq(1).text();
                var navUrl = "http://localhost:7250/GridViewRowJQuery/CustomerDetails.aspx?cid=" + firstParam + "&cname=" + secondParam;
                top.location = navUrl;                
            });
        });
Comment posted by Waseem on Thursday, April 30, 2009 6:09 AM
if the was more than one gridview it would be very simple :)
look at this line
$("tr").click(function(event) {

you would change it to
$("#GridView1 tr").click(function(event) {


explanation
$(element).click(function(event) { ... }
it is really similar to adding css
# for ID
. for class
so the gridview id is "GridView1"
so we say #GridView1
but we want the tr element so we say
#GridView1 tr
Comment posted by Waseem on Thursday, April 30, 2009 6:12 AM
regarding conflicts :
you can say something like var $myvar = JQuery.noConflict();
so instead of $(this) you will use $myvar(this)
but using function wrappers works better
Comment posted by Waseem on Thursday, April 30, 2009 6:18 AM
Here is some code for this example to allow a hover effect per row : changes bg color

            $("tr").hover(function() {
                $(this).css({ backgroundColor:"#999999"});
            }, function() {
                $(this).css({ backgroundColor: "#ffffff" });
            });
Comment posted by Waseem on Thursday, April 30, 2009 6:25 AM
Here is some code for this example to allow a hover effect per row : changes bg color

            $("tr").hover(function() {
                $(this).css({ backgroundColor:"#999999"});
            }, function() {
                $(this).css({ backgroundColor: "#ffffff" });
            });
Comment posted by Suprotim Agarwal on Monday, May 4, 2009 12:08 AM
Waseem: Thanks for your tips. They have been covered earlier over here

http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=63
Comment posted by ganesh on Tuesday, December 7, 2010 10:29 PM
Hi, Pls help to solve my issue. i have two gridview and one asp.net button. In first gridview 2 columns will be there one is checkbox and another is Text type. Number of rows will be there and i choose( using checkbox ) more than one rows and click the button, based on my selection ( checkbox selection ) another set of records will be loaded in 2 gridview.

pls help me help.

Thanks in advance.
Comment posted by Suprotim Agarwal on Wednesday, December 8, 2010 4:58 AM
Ganesh: Show me the code you have written so far!
Comment posted by biswaranjan on Wednesday, February 15, 2012 12:57 AM
The last line
var navUrl = "http://localhost:7250/GridViewRowJQuery/CustomerDetails.aspx?cid=" + firstParam + "&cname=" + secondParam;

helped a lot ................Thankssssssssssssssssssssssssssssss