GridViews are great for showing tabular, repeated data. As with all tabular data, sometimes your dataset has too many fields to show within the table. Therefore, you need to make the row “clickable” so you can show the further detail to the user. You may post the record ID to a view page or even popup the record detail in a JQuery dialog. There are many ways to show the detail so you should consider which approach is best for your site navigation. This article discusses how to select a row on a GridView and do something with it. A perfect scenario for this technique is a GridView that, when a row is selected, refreshes a child GridView and show hierarchical data.
The native row selection method for an asp: GridView is to add a button labeled “Select” at the beginning or end of the row. Then the user clicks the select button which executes code to show the detail. To make navigation easier for the user, I like to make the row row “selectable” so the user does not have to click the button to generate the view. (Note: this is also an accessibility issue too).
Note the asp: CommandField added to the GridView. This will add a SELECT button to the GridView, however the Visible = “false” means it is not shown in the markup. We do not need it in the markup, because we will handle the functionality in the codebehind. But we will bind the codebehind to the CommandField. To do this, we need to bind the row OnClick event to the GridView (I called my GridView GridView1 ) row select functionality. We do this in code as below.
protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
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.GridView1, "Select $" + e.Row.RowIndex);
So what is happening here is:
- When the Row data is bound to the GridView
- Set attributes on the row
- OnMouseOver – change the cursor and underline the text
- OnMouseOut – remove the text underline
- OnClick – call the GridView select method
Each line then has active style changes in response to mouseover / out events and will respond to an OnClick event. You can configure this event as you would normally do so in the asp: CommandField. Alternately, you could bind the OnClick event to another asp: CommandField function is the default action for a row click needs to be an update or insert call.
Til next time.