Pass Multiple Values from a GridView to Another Page using ASP.NET

Pass Multiple Values from a GridView to Another Page  using ASP.NET

A common requirement in our projects is to select a GridView row and pass multiple values of the selected row to another page. I recently got a request from a few readers who wanted an article on this. In this article, we will explore how simple it is to achieve this requirement.

I assume you have some basic understanding of the GridView and how to bind it to a Data Source control. The Hyperlink control added to the GridView makes it quiet easy to select a row and send single/multiple values to a different page through the URL. Let us see how:

Step 1: Create a new ASP.NET website. Drag and drop a SqlDataSource Control to the 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>

Step 2: 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>

Step 3: 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’.

Step 4: Go back to Default.aspx and add two hyperlink fields. We will see how to pass a single value as well as multiple values using the two hyperlink fields.

Single Value:

Add the following hyperlink control after the <Columns> tag in the GridView as shown below:

<Columns>
<asp:HyperLinkField DataNavigateUrlFields="CustomerID" DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}" Text="Pass Single Value" />

Multiple Values:

Just below the first hyperlink field, add another hyperlink field as shown below:

<asp:HyperLinkField DataNavigateUrlFields="CustomerID, CompanyName, ContactName, Address, City" DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}&CName={1}&ContactName={2}&Addr={3}&City={4}" Text="Pass Multiple Values" />

In the source code shown above, we are using the hyperlink field and setting some properties that will make it extremely easy to pass values to a different page. The 'DataNavigateUrlFields' sets the names of the fields, that is to be used to construct the URL  in the HyperLinkField. In the first hyperlink, since we are passing only a single value, the DataNavigateUrlFields contains only CustomerID. However in the second hyperlink, since there are multiple values to be passed, DataNavigateUrlFields contains all the names of the fields that are to be passed as query string to CustomerDetails.aspx

Similarly, the 'DataNavigateUrlFormatString' sets the string that specifies the format in which the URL is to be created. The 'Text' property represents the text that will be displayed to the user. The entire source code will look similar to the following:

<body>
 <form id="form1" runat="server">
 <div>
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
 SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
 </asp:SqlDataSource>
 </div>
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
 DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
 <Columns> 
 <asp:HyperLinkField DataNavigateUrlFields="CustomerID" 
 DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}"
 Text="Pass Single Value" />
 <asp:HyperLinkField DataNavigateUrlFields="CustomerID, CompanyName, ContactName, Address, City" 
 DataNavigateUrlFormatString="CustomerDetails.aspx?CID={0}&CName={1}&ContactName={2}&Addr={3}&City={4}"
 Text="Pass Multiple Values" />
 <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>
 </form>
</body>

Step 5: The last step is to retrieve the query string variables from the URL in the CustomerDetails.aspx page. Add the following code for that:

C#

 protected void Page_Load(object sender, EventArgs e)
    {
 string cid = Request.QueryString["CID"];
 string cname = Request.QueryString["CName"];
 string contactName = Request.QueryString["ContactName"];
 string address = Request.QueryString["Addr"];
 string city = Request.QueryString["City"];
    }
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")
 Dim contactName As String = Request.QueryString("ContactName")
 Dim address As String = Request.QueryString("Addr")
 Dim city As String = Request.QueryString("City")
 End Sub

Set a breakpoint at the Page_Load method of the CustomerDetails.aspx. Run the application and click on either the ‘Pass Single Value’ or ‘Pass Multiple Values’ hyperlink to pass values to the CustomerDetails.aspx page. Using the breakpoint, observe the values of the selected row being passed to the CustomerDetails page.

I hope this article was useful and I thank you for viewing it.

If you liked the article

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏跟着阿笨一起玩NET

c# 使用timer定时器操作,上次定时到了以后,下次还未执行完怎么处理

------解决方案-------------------------------------------------------- 开始的时候,禁用定时器,你...

97210
来自专栏互联网开发者交流社区

AvalonJS+MVVM实战部分源码

15420
来自专栏林德熙的博客

C# 解析 sln 文件 使用

我的项目,编码工具 需要检测打开一个工程,获取所有项目。 但是发现原来的方法,如果存在文件夹,把项目放在文件夹中,那么是无法获得项目,于是我就找了一个方法去获得...

24000
来自专栏飞扬的花生

C#实现Excel模板导出和从Excel导入数据

      午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 ? 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.O...

70370
来自专栏ASP.NET MVC5 后台权限管理系统

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(23)-权限管理系统-角色组模块

接下来我们的目标是 角色组管理 角色组权限设置 用户管理 把角色组授权给用户 给用户分配角色组 所以最少我们还要讲多5讲才能结束这个管理系统,经过之前的样例程序...

34290
来自专栏哲学驱动设计

090706 T Linq 的认识

/// <summary> /// 一个不错的Linq问题 /// </summary> private void LinqQuestion() {     J...

20470
来自专栏草根专栏

设计模式学习(二): 观察者模式 (C#)

《深入浅出设计模式》学习笔记第二章 需求: 开发一套气象监测应用,如图: ? 气象站,目前有三种装置,温度、湿度和气压感应装置。 WeatherData对象追踪...

35250
来自专栏c#开发者

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

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

37340
来自专栏跟着阿笨一起玩NET

ASP.NET MVC中使用FluentValidation验证实体

本文转载:http://www.cnblogs.com/libingql/p/3801704.html

9610
来自专栏张善友的专栏

通过SmtpClient发送Exchange会议邮件

看到C#中调用Outlook API 发起会议 ,这个完全可以用SMTP方式实现的,下面我的项目中使用的代码: 对于.NET而言,从2.0开始,发邮件已经是一件...

21590

扫码关注云+社区

领取腾讯云代金券