Get the row that has been clicked in the gridview
I have added OnClick event dynamically for gridview.So when I click on any of the row on grid view, the event is fired but I can't get which row is clicked. This is the code where I add event.
protecte开发者_如何转开发d void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty);
}
//This is the code which catches this event
protected void GridView1_OnClick(object sender, EventArgs e)
{
_ID="10" //Static data. I need this from the gridview1.row[ClickedRow].cell[0]
}
I fear you'll have to "manually" assign this value.
For this, add hidden input element to the form:
<input type="hidden" name="clicked_row" />
Change the code to:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty) + "; document.forms[0].elements['clicked_row'].value = '" + e.Row.RowIndex + "';";
And finally, read the index from the Request in the GridView1_OnClick
method:
_ID = Int32.Parse(Request.Form["clicked_row"]);
If each row has its own ID change e.Row.RowIndex
to e.Row.Id
.
I think, you could pass your id/rowindex as parameter to GetPostBackClientHyperlink()
and implement the IPostBackEventHandler
-interface in your page. The RaisePostBackEvent()
method will get the id as input parameter passed in.
I haven't tested this, I just took a look at the example in MSDN documentation
Try passing in the row instead of the grid, like this:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(e.Row, String.Empty);
And in your event handler:
protected void GridView1_OnClick(object sender, EventArgs e)
{
if (sender is GridViewRow)
{
int index = ((GridViewRow)sender).RowIndex;
}
}
I'm not positive, but I think the GridView OnClick will still fire since you're passing a child element of the grid.
精彩评论