Click here to Skip to main content
15,867,756 members
Articles / Web Development / ASP.NET
Article

Clickable Rows in a DataGrid

Rate me:
Please Sign up or sign in to vote.
3.94/5 (21 votes)
1 Dec 20053 min read 182.2K   74   23
How to setup a DataGrid to accept a user's click on a row.

Sample Image - dgrowselect

Introduction

Ah, everyone's favorite tool, the DataGrid. While a great tool, it can be difficult to work with, as I'm sure you all know. In several of my page making conquests, the DataGrid was the weapon of choice for displaying data, but left a need in the user interface for the users of my site. Being confined to clicking buttons or links to edit data or to expand on a row, while still functional, it left quite a bit of confusion for first time and often repeat users. So, towel in hand, I set out to find out how to setup a DataGrid's rows to be clickable.

Background

In my quest, I had searched several sites that gave some or incomplete information on how to setup a DataGrid properly to handle Click events. After many hours of banging my head and finally getting it to work, I vowed to document it all and share the code to try to prevent some other poor soul from having to go through what I did.

Using the code

The idea behind getting this to work is to create an OnClick event for that row that mimics hitting an ASP.NET WebForm button; in my example it's the Select button. If you're not familiar with how ASP.NET's web form controls work, when you click on them, they fire a JavaScript function called __doPostBack(eventTarget, eventArgument). The control clicked passes its ID along to the JavaScript function and the function starts the postback process. Now it becomes difficult because these IDs are generated on the fly when the page is viewed, but at least in a predictable manner. While not difficult to setup, there are several small things you need to do to make everything fit together.

HTML
//The select button's code as viewed in the running page's source
<a href="javascript:__doPostBack('_ctl0$dgRequests$_ctl4$_ctl0','')">Select</a>
//The Datagrid row with our added attributes as viewed 
//in the running page's source. Notice how the onclick command 
//matches the select button above
<tr onmouseover="this.style.backgroundColor='beige';this.style.cursor='hand'" 
        onmouseout="this.style.backgroundColor='#D9E2FF';" 
        onclick="javascript:__doPostBack('_ctl0$dgRequests$_ctl4$_ctl0','')">

In my example, I mimic a Select button. So for this, I had to add a Select button column to my DataGrid. However, it doesn't need to be visible so this column can just be hidden. If this column isn't added, the Click event won't detect properly and the event listener won't know how to trigger the proper listener. Next, the OnClick event can be added to the DataGrid row. The ItemCreated event for the DataGrid is used to add the necessary JavaScript to each row. The only line that is necessary is the OnClick attribute; the first line changes the cursor to a hand cursor and changes the color of the row background, while the second line removes the color change on mouse out. I split up alternating items and items because I had my DataGrid set up for alternating colors for visibility. If you aren't playing with the colors, you can combine the if statements as you see in the second piece of code.

C#
private void dgRequests_ItemCreated(object sender, 
         System.Web.UI.WebControls.DataGridItemEventArgs e)
//For Datagrig's with alternating colors
{
    if(e.Item.ItemType == ListItemType.AlternatingItem)
    {
        e.Item.Attributes.Add("onmouseover", 
               "this.style.backgroundColor='beige';this.style.cursor='hand'");
        e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#99B3FF';");
        e.Item.Attributes.Add("onclick", "javascript:__doPostBack" + 
               "('_ctl0$DataGrid1$_ctl" + 
               ((Convert.ToInt32(e.Item.ItemIndex.ToString()))+2) + 
               "$_ctl0','')");
    }
    if(e.Item.ItemType == ListItemType.Item)
    {
        e.Item.Attributes.Add("onmouseover", 
               "this.style.backgroundColor='beige';this.style.cursor='pointer'");
        e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#D9E2FF';");
        e.Item.Attributes.Add("onclick", "javascript:__doPostBack" + 
               "('_ctl0$DataGrid1$_ctl" + 
               ((Convert.ToInt32(e.Item.ItemIndex.ToString()))+2) + 
               "$_ctl0','')");
    }
}
C#
private void dgRequests_ItemCreated(object sender, 
                  System.Web.UI.WebControls.DataGridItemEventArgs e)
//For a single color Datagrid
{
    if(e.Item.ItemType == ListItemType.AlternatingItem || 
       e.Item.ItemType == ListItemType.Item)
    {
        e.Item.Attributes.Add("onmouseover", 
               "this.style.backgroundColor='beige';this.style.cursor='pointer'");
        e.Item.Attributes.Add("onmouseout", 
               "this.style.backgroundColor='#99B3FF';");
        e.Item.Attributes.Add("onclick", "javascript:__doPostBack" + 
               "('_ctl0$DataGrid1$_ctl" + 
               ((Convert.ToInt32(e.Item.ItemIndex.ToString()))+2) + 
               "$_ctl0','')");
    }
}

If you have problems with the post back function lining up, you can unhide the Select column and look at the runtime source to see if the row postback functions match the Select button.

The rest of the code is handled in the same manner as a Select button event; set up the SelecteIndexChanged function and create the event listener. The whole thing is rather simple to set up and can be done for any of the button columns you want, saving you from the perils of user navigation issues!

A small change you will need to make if you choose to use this in VB is to change the __doPostBack function to this:

VB
e.Item.Attributes.Add("onclick", _
   "javascript:__doPostBack('dgRequests$_ctl" & _
   ((Convert.ToInt32(e.Item.ItemIndex)) + 2) & "$_ctl0','')")

Conclusion

When I started looking into this, I wasn't familiar with the __doPostBack function that ASP.NET uses, so for me it was an interesting project. It's a simple way to improve your UI, and hey, a happy user = peace and quiet! *Pulls out towel and sticks thumb out* Till next time!

History

  • 11-26-05 - Initial writing.
  • 11-28-05 - Changed the OnMouseOver event to handle Firefox better and added an OnClick event for VB.NET.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
I am Network Engineer by day and software geek by night time. I started into the software world by teaching myself basica on the old family Tandy 1000 and I've been moving up in the world ever since. I've started a computer science major at Michigan Tech University, and will eventually finish it up.

Comments and Discussions

 
QuestionFull working example? Pin
Travis Walker14-Jan-09 19:13
Travis Walker14-Jan-09 19:13 
GeneralGood article Pin
Patrick de Ruijter19-Dec-08 1:26
Patrick de Ruijter19-Dec-08 1:26 
GeneralThanks for your post Pin
rlnssaikrishna12-Nov-08 5:34
rlnssaikrishna12-Nov-08 5:34 
GeneralDataGrid DoPostBack Pin
BVPB26-Jun-07 23:08
BVPB26-Jun-07 23:08 
QuestionHelp Pin
fcp119-Jul-06 4:45
professionalfcp119-Jul-06 4:45 
GeneralLittle change in code (only for vb.net) Pin
rc_latha16-May-06 9:20
rc_latha16-May-06 9:20 
GeneralIn ASP.NET 2.0... Pin
Kacee Giger9-Jan-06 5:44
Kacee Giger9-Jan-06 5:44 
GeneralRe: In ASP.NET 2.0... Pin
yw_edin19-Jun-06 13:48
yw_edin19-Jun-06 13:48 
GeneralUsing VB Pin
gharry23-Dec-05 10:57
gharry23-Dec-05 10:57 
GeneralRe: Using VB Pin
xoxoxoxoxoxox3-Feb-06 11:52
xoxoxoxoxoxox3-Feb-06 11:52 
GeneralRe: Using VB Pin
gharry4-Feb-06 11:01
gharry4-Feb-06 11:01 
GeneralDataGrid_Select event not firing Pin
Ad@m15-Dec-05 23:17
Ad@m15-Dec-05 23:17 
GeneralRe: DataGrid_Select event not firing Pin
Mike From Oz16-Dec-05 19:03
Mike From Oz16-Dec-05 19:03 
GeneralRe: DataGrid_Select event not firing Pin
Sebina13-Aug-07 4:18
Sebina13-Aug-07 4:18 
GeneralBetter way Pin
syao16829-Nov-05 5:04
syao16829-Nov-05 5:04 
GeneralRe: Better way Pin
fulgeras7-Dec-05 21:56
fulgeras7-Dec-05 21:56 
GeneralRe: Better way Pin
Dave Hurt8-Dec-05 3:02
Dave Hurt8-Dec-05 3:02 
GeneralRe: Better way Pin
fulgeras8-Dec-05 6:24
fulgeras8-Dec-05 6:24 
GeneralRe: Better way Pin
Sigurd Johansen9-Dec-05 14:41
Sigurd Johansen9-Dec-05 14:41 
GeneralRe: Better way Pin
RMAN_OTown8-Dec-05 6:29
RMAN_OTown8-Dec-05 6:29 
GeneralRe: Better way Pin
RMAN_OTown8-Dec-05 7:50
RMAN_OTown8-Dec-05 7:50 
GeneralRe: Better way Pin
Hooded_Prince6-Mar-08 5:20
Hooded_Prince6-Mar-08 5:20 
Generalcodework Pin
xiezhenhua28-Nov-05 14:49
xiezhenhua28-Nov-05 14:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.