Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

January 25, 2010

ASP.NET: Selecting a Row in a GridView

Filed under: ASP.NET,C#,VB.NET @ 3:25 pm

Once I had my ASP.NET GridView in place (see this prior post), the next thing I wanted to do was select a row and go to a review/edit page. But I didn’t want to add the "Select" or "Edit" buttons. It seemed more natural for the users to simply click on the row.

I used Bing and followed my always helpful "guess and check" method. I found quite a few links to solutions for clicking on a row in the GridView control. Some didn’t work at all. Some worked if you turned off enableEventValidation. Some worked only if you did not try to page the results.

Here is a simple solution that works with any GridView and supports paging. It goes into the code behind file for the page containing the GridView. In this example, the GridView is called "CustomerGridView".

In C#:

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
    foreach (GridViewRow row in CustomerGridView.Rows) {
        if (row.RowType == DataControlRowType.DataRow) {
            row.Attributes["onmouseover"] = 
               "this.style.cursor=’hand’;this.style.textDecoration=’underline’;";
            row.Attributes["onmouseout"] = 
               "this.style.textDecoration=’none’;";
            // Set the last parameter to True
            // to register for event validation.
            row.Attributes["onclick"] = 
             ClientScript.GetPostBackClientHyperlink(CustomerGridView, 
                "Select$" + row.DataItemIndex, true);
        }
    }
    base.Render(writer);
}

In VB:

Protected Overrides Sub Render(ByVal writer As _
                               System.Web.UI.HtmlTextWriter)
    For Each row As GridViewRow In CustomerGridView.Rows
        If row.RowType = DataControlRowType.DataRow Then
            row.Attributes("onmouseover") = _
              "this.style.cursor=’hand’;this.style.textDecoration=’underline’;"
            row.Attributes("onmouseout") = _
              "this.style.textDecoration=’none’;"

            ‘ Set the last parameter to True
            ‘ to register for event validation.
            row.Attributes("onclick") = _
           ClientScript.GetPostBackClientHyperlink(CustomerGridView, _
                     "Select$" & row.DataItemIndex, True)
        End If
    Next

    MyBase.Render(writer)
End Sub

This code overrides the Render method for the page. It loops through each of the rows in the GridView. It sets the onmouseover and onmouseout attributes so that the user sees that the row is clickable while moving the mouse over the grid rows.

The key attribute, however, is the onclick. Setting this attribute to GetPostBackClientHyperlink allows you to get a server-side click event on the row.

The first parameter to this method is the name of the GridView control. For this example, it is CustomerGridView.

The second parameter defines the name of the command, a "$" separator, and the command argument.

NOTE: In many examples I found, the command argument is set to row.RowIndex instead of row.DataItemIndex. This does not work if your GridView is paged because RowIndex is reset to 0 for the first item on each page.

Set the last parameter of the GetPostBackClientHyperlink method to true to register the event for validation. By setting this, you don’t have to turn off enableEventValidation.

You can then catch this event using the RowCommand.

In C#:

private void CustomerGridView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select") {
        // Get the list of customers from the session 
        List<Customer> customerList =
                 Session["Customers"] as List<Customer>;

         Debug.WriteLine(customerList[Convert.ToInt32(e.CommandArgument)].LastName);
    }
}

In C#, you also need to set up the event handler. In this example, the event handler is set up in the Page_Load event, but you could put it where it makes sense for your application.

CustomerGridView.RowCommand += CustomerGridView_RowCommand;

In VB:

Private Sub CustomerGridView_RowCommand(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
            Handles CustomerGridView.RowCommand
    If e.CommandName = "Select" Then
        ‘ Get the list of customers from the session
        Dim customerList As List(Of Customer)
        customerList = TryCast(Session("Customers"),  _
                                 List(Of Customer))

        Debug.WriteLine(customerList(CType(e.CommandArgument, Integer)).LastName)
    End If
End Sub

This code first gets the customer list from the session. You can get the GridView information from wherever you have it defined, such as the ViewState. A Debug.WriteLine statement demonstrates how to access the CommandArgument. In a real application, you would use the CommandArgument to display the Review/Edit page for the selected customer.

Use this technique any time you want to handle a click event on an ASP.NET GridView row.

Enjoy!

31 Comments

  1.   Rasha G. SAlim — April 3, 2013 @ 6:38 am    Reply

    GREAT ARTICLE!!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2023 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs