There are many ways to select a row and perform whatever actions you desire in GridView. The easiest is to let its CommandField generate the select button and use the SelectedIndexChanging and SelectedIndexChanged events for the actions desired.
<asp:CommandField ShowSelectButton="true" />
However, it would be more elegant if you can just select the row. 3 steps needed in order to achieve that:
Step 1: Add the SELECT command in RowDataBound event to each row (Assuming the ID of your GridView is “myGridView“)
protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // Just adding styles and effects e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.myGridView, "Select$" + e.Row.RowIndex); } }
Step 2: Register these SELECT commands in Render to avoid the Event Validation errors
protected override void Render(HtmlTextWriter writer) { for (int i = 0; i < this.myGridView.Rows.Count; i++) { Page.ClientScript.RegisterForEventValidation(this.myGridView.UniqueID, "Select$" + i); } base.Render(writer); }
Step 3: Use the SelectedIndexChanging and SelectedIndexChanged events for the actions desired
November 19, 2008 at 5:18 am
Thanks a lot for step 2.
April 14, 2009 at 5:46 am
I have written as the code above, my page however does a post back but does not hit the selectedindexchanged or selectedindexchanging events. I am using AJAX, does scriptmanager has got to do anything.
September 4, 2009 at 9:58 am
Works great! Thanks a lot!