Reputation: 4412
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.
Upvotes: 1
Views: 17502
Reputation: 2070
Here is another way if you are not using DataKeyNames.
int RowIndex;
protected void gvName_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvName.SelectedRow;
string name = gvName.Rows[RowIndex].Cells[1].Text; //Gets column
//With DataKey
string name = gvName.DataKeys[RowIndex]["TicketId"].ToString();
Response.Redirect("~/secondpage.aspx?ServiceCenter=" + name);
}
protected void gvName_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Gets Gridview row number when clicked
RowIndex = Convert.ToInt32(e.CommandArgument);
}
Upvotes: 2
Reputation: 1688
I would use Session. So I imagine that you have some variable
var currentGridViewRow = GridView.SelectedRow;
You can insert to the session information about this row:
Session["currentGridViewRow"] = currentGridViewRow;
After that in your second code behind you get the information from the session.
var currentGridViewRow = Session["currentGridViewRow"];
Please remember that this is very simple and general approach. It is good practice to write some class which will manage your session.
Helpful link: http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx
Upvotes: 1
Reputation: 1619
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"];
Upvotes: 7