Selecting a row in gridview then passing the selected row to another page

Master Yoda picture Master Yoda · Jun 19, 2013 · Viewed 16.3k times · Source

I am writing a web application in ASP.NET using C# with SQL Server.

Basically I want to be able to select a specific row in a GridView and pass the primary key from that row to another page which contains a series of text boxes and labels, I want these to be populated with the data from the selected row.

The main reason for me doing this is because I have a lot of fields in my table and I need to expand on the fields in the GridView for editing etc.

I have researched a bit about the select statement in ASP.NET but I can't figure out how to pass that information to another page.

Answer

Ben Gulapa picture Ben Gulapa · Jun 19, 2013

One way to do this:

First, in your gridview, add the primary key in the datakeys,

DataKeyNames="Id"

and add an event for the selection,

OnSelectedIndexChanging="OnRowSelected"

Then in your code behind:

protected void OnRowSelected(object sender, GridViewSelectEventArgs e)
{
    // Get the datakey of the selected row
    var id = Convert.ToInt32(grdCompany.DataKeys[e.NewSelectedIndex].Value);
    // Redirect to second page
    Response.Redirect("SecondPage.aspx?Id=" + id);
}

Then in your SecondPage.aspx, you can get the id from the selected row by:

var id = Request.QueryString["Id"];