Create new account I forgot my password    

Using ASP.NET and jQuery to Pass Multiple Values from a GridView to Another Page
Rating: 24 user(s) have rated this article Average rating: 4.3
Posted by: Suprotim Agarwal, on 12/24/2008, in category "jQuery and ASP.NET"
Views: this article has been read 36516 times
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









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
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 04, 2009 12:08 AM
Waseem: Thanks for your tips. They have been covered earlier over here

http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=63

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER