Reputation: 131
First of all, I am a new C# developer and I need some help please, I have a grid view with its SqlDataSource in my aspx file that contains 3 columns ID/Name/Job and several records(rows). When the user selects a row, I would like to redirect to another page and pass as a parameter the value of the selected ID of the row. Users are permitted to select only one row each time. I spent several hours on that however something strange is happened.
I have a method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string selectedID;
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = e.Row;
selectedID = (GridView1.DataKeys[e.Row.RowIndex].Value.ToString());
gvr.Attributes.Add("OnClick","javascript:location.href='Views/EditMenus/EditCompany.aspx?id=" + selectedID + "'");
gvr.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFE6E6'");
gvr.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
gvr.Attributes.Add("style", "cursor:pointer;");
Session["IDs"] = selectedID;
} }
In my redirect page I have in page load method the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IDs"] != null)
{
Label2.Text = "Selected ID is: "+ Session["IDs"].ToString();
}
}
Now, when I select a row, the redirection to the other page works correctly and the browser url has the correct value of the selected ID according the javascript code above, however the Label2.Text prints a wrong ID. Instead of the value of the selected ID, it prints the value ID of the last row of each page. Why that happens?
It's a bit strange for me since I am using the same variable "selectedID" for both cases as you can see above.
Upvotes: 2
Views: 4017
Reputation: 6996
You need to sore value of your ID
in Session
variable on SelectedIndexChanged
event of your GridView
void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row.
//Because the SelectedIndexChanging event occurs before the select operation
//in the GridView control, the SelectedRow property cannot be used.
//Instead, use the Rows collection
//and the NewSelectedIndex property of the
//e argument passed to this event handler.
GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
//Cells[0] is for first column so assign according to your column for ID
Session["IDs"]=row.Cells[0].Text;
}
Upvotes: 1