65.9K
CodeProject is changing. Read more.
Home

Select GridView Row By Clicking Anywhere In Row

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.40/5 (4 votes)

Sep 8, 2014

CPOL

1 min read

viewsIcon

18539

How to modify an ASP.NET GridView so that clicking anywhere in a row will select that row.

Introduction

There are lots of articles around on how to modify a GridView so that clicking anywhere in a row selects that row, rather than having to use a clunky Select button. However, I found them all to be unnecessarily complicated, so I came up with a solution I found a bit more elegant.

Using the Code

This is a simple solution. Go ahead and create your ASP.NET page and add your GridView, bind it to a DataSource and so on. Once your page is working, add the code below to the RowDataBound event of the GridView:

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

         If e.Row.RowType = DataControlRowType.DataRow Then
             Dim b As Button = New Button
             b.CommandName = "Select"
             b.CssClass = "hidden"
             Dim c As TableCell = New TableCell
             c.CssClass = "hidden"
             c.Controls.Add(b)
             e.Row.Controls.Add(c)
             e.Row.Attributes.Add("onclick", "__doPostBack('" & b.UniqueID.ToString & "','');")
          End If

    End Sub

I don't have a listing in C#, but there are several good conversion tools available online - just search for "Convert VB.NET to C#". I haven't uploaded any source code as I think this really shouldn't be necessary for such a simple piece of code.

Just to explain the code, all it does is it creates a new column in the GridView, which is hidden by assigning it the CSS class "hidden", which is defined in my stylesheet as simply:

display:none;

To the hidden column, the code then adds a new button, also hidden using the same CSS class, and this button has a CommandName of "Select", meaning that when it is clicked, the row is selected using the built-in GridView code.

However, the button can't be clicked because it's hidden. Instead, we add code to the OnClick event of the row which calls a tiny bit of JavaScript that triggers a postback as if the new button had been clicked, thus selecting the clicked GridView row.

For best results, I recommend placing the GridView inside an UpdatePanel so that a full page postback isn't triggered.

History

  • 8th September 2014: Initial post