Passing GridView Values
By AzamSharp
Views: 32858

Introduction:

In this article I will show you that how you can pass the values from the GridView control to other pages. We will see some of the common scenarios in which you wish to pass the values to different pages. The article is also supplemented with code so please feel free to download it.

Using bound columns with select columns:

Let's first examine the most basic scenario. In this you are displaying the data in the GridView control using the BoundColumns and you want to click on the select column and get the value of the primary key or any other column. Once you have displayed the columns on the GridView control using the BoundColumns. You can access the select link button using the "SelectedIndexChanged" event of the GridView control.

Check out the code below:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

/* In the line below you can retreive the value of the CategoryID

* But the CategoryID is displayed on the page which is not a good idea

You can easily set the visible property of the CategoryID column to false but you

will still be able to access the value of the CategoryID*/

Response.Write(GridView1.SelectedRow.Cells[0].Text);

}

As, you have noticed that since I am using BoundColumns to access the value of the first column using the Cells property. Although this will work as expected but this is not a very good solution. The problem with this approach is that when you switch the columns from one to three or any other way you will be forced to change the code behind to reflect those changes so that the Cells property will target the correct column.

Most of the time you don't want to display the primary key of the table which in this case is CategoryID. You can make the CategoryID column invisible by using its property visible = false.   

Using template column with select columns:

This is a much better approach since now your GridView is no longer dependent on the position of the columns in the GridView control. Let's see some code that is used to generate the template columns of the GridView control.

<asp:TemplateField HeaderText="CategoryID" Visible="False">

<ItemTemplate>

<asp:Label ID="lblCategoryID" runat="server" Text='<%# Eval("CategoryID") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="CategoryName">

<ItemTemplate>

<asp:Label ID="lblCategoryName" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Description">

<ItemTemplate>

<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Link">

<ItemTemplate>

As, you can see in the code above I have used ASP.NET Label control to bind the text from the database. And check out the code below which shows how we can access individual columns.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

string selectedText = ((Label)GridView1.SelectedRow.FindControl("lblCategoryID")).Text;

Response.Write(selectedText);

}

As you can see in the code above the columns are no longer dependent on the position of the cell index.

Generating links inside GridView control from id from database:

You might find this the most important. Many times we have a hyperlink inside the GridView control and we want that hyperlink to go to certain page based on the id present in the database. I will tell you a very simple and easy way to accomplish this thingy :).

First make a hyperlink column inside the GridView control.

<asp:TemplateField HeaderText="Link">

<ItemTemplate>

<asp:HyperLink ID="hlUrl" runat="server" NavigateUrl='<%# FormatUrl( (int) Eval("CategoryID") ) %>' Text = '<%# Eval("CategoryName") %>' />

</ItemTemplate>

</asp:TemplateField>

Let's first see the Text property which is binds the "CategoryName". "NavigateUrl" property calls a method which is named "FormatUrl". The FormatUrl takes an integer parameter which in this case is "CategoryID". Let's now look at the FormatUrl method which is defined in the code behind of the aspx page.

// This method is used to generate a new url

protected string FormatUrl(int categoryID)

{

if (categoryID < 1)

throw new ArgumentOutOfRangeException("CategoryID");

return "CategoryDetails.aspx?categoryID=" + categoryID;

}

FormatUrl method is pretty simple to understand. It take a categoryID which is of type Int32. If the categoryID is less than 1 then there is some error and hence we throw an exception. If however the categoryID is greater then 0 then we simply concatenates the categoryID with the string url and return the newly generated url back to the GridView control.

Sending Mulitple Values from GridView to different page:

I think I have discussed this issue lot of times in my previous articles. But here it is once again. If you want to select multiple values from the GridView control and send to a new page you can easily do this by using checkboxes inside the GridView control which will enable you to select multiple items. After selecting the items you need to code for the ASP.NET Button server control which will send the selected values to the new page.

Let's take a look at the code:

protected void Button1_Click(object sender, EventArgs e)

{

ArrayList selectedValues = new ArrayList();

// This will select multiple items

foreach (GridViewRow row in GridView1.Rows)

{

bool result = ((CheckBox) row.FindControl("CheckBox1")).Checked;

if (result)

{

int categoryID = Convert.ToInt32(((Label)row.FindControl("lblCategoryID")).Text);

selectedValues.Add(categoryID);

}

}

// Put the selected values in the Session to be used in a different page

Session["SELECTEDVALUES"] = selectedValues;

// transfer to a new page

Response.Redirect("NewPage.aspx");

}

 

And here is the code for NewPage.aspx:

if (!Page.IsPostBack)

{

// Check that if the session object contains anything or not

if (Session["SELECTEDVALUES"] != null)

{

ArrayList selectedValues = (ArrayList)Session["SELECTEDVALUES"];

// print out the values

foreach (int intValue in selectedValues)

Response.Write(intValue);

}

}

Using HyperLinkColumn to send the values to a new page:

The last technique I will discuss is that if you want to use the HyperLinkColumn to pass values to a new page. This is probably the easiest of them all. Let's take a look how this is done. First thing you need to do is to add a new HyperLinkColumn.

<asp:HyperLinkField DataTextField="CategoryName" DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="NewPage.aspx?id={0}"

HeaderText="HyperLink Column" />

The DataTextField property is used to display the text on the screen. In this case I have set it to "CategoryName" which means "CategoryName" will be displayed as Text inside the GridView control.

"DataNavigateUrlFields" represents what you want to send to the next page which in this case is "CategoryID".

"DataNavigateUrlFormatString" property represents which page you want to send the value. In this case it is NewPage.aspx and it will be in the querystring variable called id.

You can easily receive the values send by the HyperlinkColumn using the following code:

if (Request.QueryString["id"] != null)

{

int yourValue = Convert.ToInt32(Request.QueryString["id"]);

}

 

As, you can see how easy it is to send as well receive the values. I know you must be wondering how you can pass multiple values. Well, its pretty simple. Check out the code below:

<asp:HyperLinkField DataTextField="CategoryName" DataNavigateUrlFields="CategoryID,CategoryName" DataNavigateUrlFormatString="NewPage.aspx?id={0},CId={1}"HeaderText="HyperLink Column" />

 

Simply, separate the column names using comma and that's it.

I hope you liked the article, happy coding!

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: asp:HyperLinkField
Name: Enrique J. Diaz
Date: 4/3/2007 5:56:13 AM
Comment:
Can we have a litle chat to ask you some questions about HyperLinkField? Please contact me on my email or feel free to add me to you msn(neozaid@hotmail.com) or yahoo msn(horuzaid@hotmail.com.

Sincerely,
Enrique
Subject: Main
Name: ramesh
Date: 4/16/2007 3:47:02 AM
Comment:
good one
Subject: DataNavigateUrlFields
Name: Trucidation
Date: 5/24/2007 1:12:48 AM
Comment:
I'm using ASP.Net v1.1, apparently DataNavigateUrlField is still singular, not plural. Is there any way of passing multiple values in v1.1?
Subject: datakeynames value
Name: Geisel
Date: 5/30/2007 12:23:18 PM
Comment:
I have a gridview with a template column with an image button when it is clicked I wanted to get the selected row or the datakeyname value of this line item this code is executing under the
Public Sub dgcases_OnRowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "imageswap" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim lineitem As String = CType(Me.dgcases.DataKeys(index).Value, String)
Endif
I get an error of input string not in the correct format. Any help would be great. Thank you.
Subject: found error
Name: henrik a
Date: 6/2/2007 3:17:44 PM
Comment:
first thanx for this great site i have found answer to most of my gridview ? here.

but you made a small mistake when you pass multiple values its not NewPage.aspx?id={0},CId={1} but
NewPage.aspx?id={0}&CId={1}
Subject: RE: Found Error
Name: AzamSharp
Date: 6/3/2007 10:53:42 AM
Comment:
Hi,

I have ran the code with the comma and it works fine. Run the code and let me know.

Thanks,
Azam
Subject: Passing Gridview to gridview
Name: Paul
Date: 6/19/2007 9:36:56 AM
Comment:
Hi,

How do I pass the data from gridview of the Child window to the Parent window's GridView/DetailsView (in Edit mode) using the Select ButtonField of GridView

and OnRowCommand="grid_RowCommand"

Thanks.
Subject: Passing Values from Child to Parent
Name: AzamSharp
Date: 6/21/2007 9:00:30 AM
Comment:
You can take a look at the following article:

http://gridviewguy.com/ArticleDetails.aspx?articleID=126
Subject: Very very Thanks
Name: Deepak
Date: 6/25/2007 4:11:20 AM
Comment:
Thanks you to post this artile this is realy usefull for me.
Subject: receiving data at the other page
Name: Kamy
Date: 7/7/2007 12:46:42 AM
Comment:
Hi, Can you please send a reply soon..

I am sending a value through a grid view to a page default2.aspx



I am filling this by sending a query to a database.

then on the other page i have the following code

SelectCommand="select distinct ra.AppId, ra.AppName as 'Application Name', ra.Description, rd.DBAFirstName + rd.DBALastName as 'DBA', rd.Region, case rad.Product when 'ASE' then 'Sybase' when 'Oracle' then 'Oracle' when 'MS SQL Server' then 'MS SQL Server' end as Product from Report.Application ra join Report.ApplicationDBA rad on ra.AppId=rad.AppId join Report.DBA rd on rad.DBA=rd.DBA" FilterExpression = "AppName={0}">

QueryStringField="ra.AppName" />


i want to display info abt the seleted element in the gridview..

i am not being able to do tht.. infact my query displays everything.. all the data..like a simple select query

Subject: asp:hyperlink in grideview problem
Name: sandip
Date: 7/8/2007 9:56:54 PM
Comment:
hi
i have one grideview in which i use hyperlink & normal button in each row now i want hyperlink value to next page on click on button in that row for that i use
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "redirect")
{

// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);

// Get the Text of the ID button control

string id2 = GridView1.Rows[index].Cells[2].Text;
//cell[2] is hyperlink colunn but it not work?
give me sol. for that
Subject: Cool
Name: Pamela
Date: 9/14/2007 5:47:29 AM
Comment:
The code that you provided above is very simple and easy to use thankx a lot for a simple well done
Subject: best description
Name: vishal
Date: 10/9/2007 11:47:07 AM
Comment:
Hii..
I have gone through your description abt hyperlink column to grid..& i found its best among what i searched on net..
thanks for taking efforts to post it the way u have posted..
god bless..
Subject: Help me I want to send the all selected row value to next page
Name: rahul
Date: 10/25/2007 7:58:26 AM
Comment:
Hi i want to send the multiple value from one page to another page.I have used the query string method but its not working.In my application i have 3 columns.First column contain hyperlink next two columns having bound column.If i click the any one of the row in first column linkbutton the the 2nd and 3rd column value of selected row should be send to another page.If i tried to pass the 3 values the linkbutton is not displayed...
Subject: Code Help
Name: Dhaval
Date: 11/20/2007 1:51:52 AM
Comment:
Hi there

I am using a javascript instead of any particular URL

However wen i set above stated 2 properties of Hyperlink column and set Navigateurl property of hyperlink to nothin, it does not give it a Linl. It shows it as plain text.

Plz Help m really stuck with it
Heres my code



Subject: gridview hyperlinks
Name: Binju
Date: 11/26/2007 4:58:26 AM
Comment:
hi
I need to give multiple parameters to my grid view links. One parameter value is databound and the another should be from the page variable. i am not able to add the second one
Subject: passing a "Date" as parameter in gridview
Name: bryan
Date: 1/30/2008 10:32:16 PM
Comment:
hi,
your codes are working but when I tried to pass a "Date" as one of the parameters, the hyperlink did not worked. is it not possible to include "Date" as parameter?

hope to hear from you soon....
Subject: appreciation
Name: Asghar
Date: 2/3/2008 9:59:33 AM
Comment:
Hi,

Thanks Azam, you blog helped me to solve my issues.

Thanks a lot
http://www.aliwebdev.com
Subject: thanx
Name: vivek
Date: 3/7/2008 6:35:09 AM
Comment:
the article was really helpful
thanx a lot
Subject: How to pass multiple querystring variables using Gridview's HyperLinkField
Name: maheshjk
Date: 3/11/2008 11:44:13 PM
Comment:
Hi,
I tried as mentioned above i.e

HyperLinkField DataTextField="CategoryName" DataNavigateUrlFields="CategoryID,CategoryName" DataNavigateUrlFormatString="NewPage.aspx?id={0},CId={1}"HeaderText="HyperLink Column"

But its not working. Throwing the below error message.
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Pls do the needful.
I need to pass 3 querystring variables to new page




Join WebHost4Life.com






Copyright GridViewGuy 2007-2008