GridView Highlight Selected Row

Posted: September 27, 2010 in ASP.Net

If you want to highlight a GridView row when it is selected, you can try the following:
ASP.Net (Design)

<asp:GridView id="grd_name" runat="server">
    <Columns>
        <asp:TemplateField HeaderText="First Name">
            <ItemTemplate>
                <asp:Label ID="lbl_first_name" runat="server" Text='<%# Eval("first_name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <SelectedRowStyle BackColor="#FFA20C" /> <!-- Set you colour here -->
</asp:GridView>

ASP.Net (Code Behind)
Now add some code to Override the Render event:

' Override the render method to provide onclick event on the gridview
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    ' Handle onclick event from GridView control
    If grd_name.Rows.Count > 0 Then
        For Each row As GridViewRow In grd_name.Rows
          If row.RowType = DataControlRowType.DataRow Then
              row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(grd_name, "Select$" + row.RowIndex.ToString, True))
          End If
        Next
     End If
     MyBase.Render(writer)
End Sub

Now add some code for when the index is changing on event SelectedIndexChanging:

 ' Routine for when a row is selected from the gridview
Protected Sub p_grd_name_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grd_name.SelectedIndexChanging
    ' Add code here
End Sub
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s