ASP.NET: Selecting a Row in a GridView

Posted Mon, Jan 25 2010 13:25 by Deborah Kurata

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!

Filed under: , , , ,

Comments

# re: ASP.NET: Selecting a Row in a GridView

Tuesday, January 26, 2010 12:12 AM by John Walker

Helpful code Deborah. Thanks. Getting good stuff from these posts.

# re: ASP.NET: Selecting a Row in a GridView

Wednesday, April 07, 2010 8:40 AM by Joris Zwaenepoel

Hi,

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

However, with a regular select button you can choose whatever value you want to be the commandargument.  Is it possible with this technique to give a commandargument other than the DataItemIndex?  I would like to use a Customer.ID instead, but if I use that instead of the DataItemIndex (after the $ separator), the SelectedIndex of the GridView is no longer correct.

# re: ASP.NET: Selecting a Row in a GridView

Friday, April 30, 2010 8:14 PM by WilliamRich

Installs in minutes and works great! Providing solutions in both C# and VB was a big help.  I will come to you first for my next solution. Thank you.

# re: ASP.NET: Selecting a Row in a GridView

Friday, April 30, 2010 10:40 PM by WilliamRich

"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."

Oddly, I could only get things to work  if I used row.RowIndex. With row.DataIntemIndex, the row selected template would kick in, and the slaved grid view would refresh, only on the first page. I suspect those functions require page-relative row indexing. In any event, it works -- for now!

# re: ASP.NET: Selecting a Row in a GridView

Wednesday, July 14, 2010 6:42 AM by phill

Thank you so much for your solution.

works great :)

# re: ASP.NET: Selecting a Row in a GridView

Thursday, August 12, 2010 10:04 AM by Arnold Kaswa

You just made my day! Excellent solution!

# re: ASP.NET: Selecting a Row in a GridView

Friday, August 20, 2010 6:54 PM by alex

good

# re: ASP.NET: Selecting a Row in a GridView

Sunday, September 26, 2010 2:08 PM by Peter

Excellent example exactly what I was looking for!

# re: ASP.NET: Selecting a Row in a GridView

Thursday, October 21, 2010 4:40 AM by Venu Vedam

Excellent solution. Thank you very much.

# re: ASP.NET: Selecting a Row in a GridView

Thursday, October 21, 2010 6:04 AM by Daniel

Hello, first of all thanks for you samples codes. It work perfect for me. Have just a little problem. When the user click on a row, I want the cell content of my first column to be displayed in a label. Can't get this to work. Can you help me please

# re: ASP.NET: Selecting a Row in a GridView

Sunday, October 24, 2010 10:52 PM by Pat

I am a newbie and this was WONDERFUL!!!!

Thank you so much! You saved me from pulling my hair out!!

# re: ASP.NET: Selecting a Row in a GridView

Tuesday, November 02, 2010 9:42 PM by Eranda Ketawalage

Its working perfectly..Thank you very much!!!

# re: ASP.NET: Selecting a Row in a GridView

Tuesday, December 07, 2010 10:39 AM by brenden

Just tried it with my dynamically created gridview and on the first page the rows are clickable and passes the correct command argument, but for the other pages rows are not clickable. I'm guessing the render method is not being fired on postback?? How would I be able to solve this?

# re: ASP.NET: Selecting a Row in a GridView

Monday, January 03, 2011 4:19 AM by Ziggynet

This is great and works correctly thanks. Do you have any idea on how to select mulltiple rows using this method.?

# re: ASP.NET: Selecting a Row in a GridView

Friday, May 13, 2011 5:00 AM by Santosh Dash

ThankYou, BOSS, You resolve my issue

# static SelectedRow after chenging page

Friday, June 10, 2011 7:48 AM by Gluck

Hi,

i've a problem.

I click a row (example 4th), after chenge page or filter but remaining selected 4th row.

(please Forgive the poor language)

# re: ASP.NET: Selecting a Row in a GridView

Monday, June 20, 2011 3:05 PM by peter

I have problem for the last code, can anybody help me how to implement these codes to our own gridview?

List<Customer> customerList =

                Session["Customers"] as List<Customer>;

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

# re: ASP.NET: Selecting a Row in a GridView

Monday, June 20, 2011 3:07 PM by peter

I have problem for the last codes:

How to implement the List<Customer> in our own gridview?

thanks

List<Customer> customerList =

                Session["Customers"] as List<Customer>;

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

# re: ASP.NET: Selecting a Row in a GridView

Tuesday, June 21, 2011 9:45 AM by Deborah Kurata

Hi Peter -

The code for the Customer class is provided in this prior link:

msmvps.com/.../asp-net-gridview-and-business-objects.aspx

Hope this helps.

# re: ASP.NET: Selecting a Row in a GridView

Wednesday, August 31, 2011 2:55 PM by Gunther

Tried using this with the Edit$ command (instead of Select$) so a user can click anywhere on the row and enter the row edit mode.

This seemed to work except that when the user clicks the next textbox, the edit command fires again and the contents of the previous textbox revert back to the previous value.

Have you used this technique for the Edit$?

# re: ASP.NET: Selecting a Row in a GridView

Tuesday, October 18, 2011 2:19 PM by Umesh Bhavsar

Thanks a lot. It's working for me. I actually followed so many posts but this one is simply great.

Thanks again.

# re: ASP.NET: Selecting a Row in a GridView

Thursday, October 27, 2011 12:09 PM by Vibhu

Thanks for the help

# re: ASP.NET: Selecting a Row in a GridView

Monday, November 14, 2011 4:50 AM by nalaka256

I was looking for this.. Thanks.. Works perfectly.

# re: ASP.NET: Selecting a Row in a GridView

Wednesday, December 07, 2011 1:42 PM by steven mandel

thanks so much - worked like a charm

# re: ASP.NET: Selecting a Row in a GridView

Monday, February 06, 2012 1:33 AM by Deep

Thanx it works.

Still multiple row selection is not supported.

I've another way, wanted to share with you all..

step 1)

       protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)

       {

           if (e.Row.RowType == DataControlRowType.DataRow)

           {

               e.Row.Attributes.Add("OnClick", "SendIndex('" + e.Row.RowIndex.ToString() + "')");

           }

       }

step2)

   <script type="text/javascript">

       function SendIndex(index) {

           var c = document.getElementById("HiddenField1");

           c.value = index;

           document.forms['form1'].submit();

       }

   </script>

step3)

       protected void Page_Load(object sender, EventArgs e)

       {

           if (Page.IsPostBack)

           {

               GridView1.SelectedIndex = int.Parse(HiddenField1.Value);

           }

       }

We can enhance it further to support multiple Row Selection

# re: ASP.NET: Selecting a Row in a GridView

Friday, March 23, 2012 5:07 AM by Harris

Great work!! helped me a lot !! thanx !

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: