Click here to Skip to main content
Click here to Skip to main content

Click/select row in ASP.NET GridView or HTML table

, 4 Jun 2013
Rate this:
Please Sign up or sign in to vote.
Make entire table row clickable/selectable by adding "onclick" event and formatting features via JavaScript and CSS3.

Introduction

The suggested technique applies to ASP.NET GridView objects, and essentially to any HTML Table tr element. First, it makes the entire GridView row object (rendered as "tr" element) "clickable" by adding the onclick event (see Listing 1 in C#). The associated event handler procedure performs the custom formatting of the clicked/selected row to make it visually different from the others in the same table (see Listing 2 for JavaScript code snippet implementing this feature).

Demo

Click on the image below to open the functional demo of the embedded YouTube video player, demonstrating the suggested technique:

YouTube Embedded Video


Fig 1. Demo snapshot demonstrates the table row corresponding to item 6 has been selected by modifying text attributes in the first cell.

Listing 1: Add onclick event (C# code behind)

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e){
    if (e.Row.RowType == DataControlRowType.DataRow){
        // javascript function to call on row-click event
        e.Row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
    }
}

Listing 2: Add JavaScript function to the page head section

<script type="text/javascript">
// format current row
function SelectRow(row) {
 var _selectColor = "#303030";
 var _normalColor = "#909090";
 var _selectFontSize = "3em";
 var _normalFontSize = "2em";
 // get all data rows - siblings to current
 var _rows = row.parentNode.childNodes;
 // deselect all data rows
 try {
     for (i = 0; i < _rows.length; i++) {
         var _firstCell = _rows[i].getElementsByTagName("td")[0];
         _firstCell.style.color = _normalColor;
         _firstCell.style.fontSize = _normalFontSize;
         _firstCell.style.fontWeight = "normal";
     }
 }
 catch (e) { }
 // select current row (formatting applied to first cell)
 var _selectedRowFirstCell = row.getElementsByTagName("td")[0];
 _selectedRowFirstCell.style.color = _selectColor;
 _selectedRowFirstCell.style.fontSize = _selectFontSize;
 _selectedRowFirstCell.style.fontWeight = "bold";
}
</script>

Development Notes

Note 1: Event-binding could also be done on the client side, for example, using jQuery .click() event. For mostly didactic purposes, it's implemented here using C# and the DataRowBound event to be consistent with core .NET technology set.
 
Note 2: In order to select/play the first item in the grid on "page load" event, use the jQuery code snippet shown below (it inserts a small time delay):

$(document).ready(function () { 
  // start the first item after small delay 
  setTimeout('PlayRowItem()', _initDelay); 
});

Note 3: As it's been pointed out in the comments, visual effects could be applied to the selected row by using a pair of addClass() and removeClass() jQuery methods. Styling the rows via CSS3 and jQuery rather than directly modifying elements' properties via jQuery as shown in Listing 2. should be considered a preferable approach for future web development, but be aware that certain deficiencies have been reported in regards to these methods prior to jQuery version 1.4.2 (starting from that version and going forward, both methods works seemingly well in all major web browsers).

Additional Resources

GridView/Table rows alternate formatting technique is described here: Alternate Rows in HTML5 Tables GridView [^].
 
Embedded YouTube SDK is available on CodeProject at:
  1. YouTube™ API for ASP.NET[^]
  2. YouTube™ Embedded Video Player: Extended API (C#)[^]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DrABELL
President Infosoft International Inc
United States United States
Dr. A. Bell has 20+ years of Software and Electrical Engineering experience. He is Win/Web veteran, published 200+ articles and authored 37 inventions, currently focused on: Windows 7/8, HTML5, CSS3, jQuery, SQL, .NET, ASP.NET, WPF, C#, Speech Technology and Mobile apps. He's been among recent App submission winners (The Windows 8* & Ultrabook™ App Innovation Contest 2012). Sample pubs:
  1. Edumatter M12: School Math Calculators and Equation Solvers (contest winner)
  2. Engineering Calculator VOLTA-2013 (contest winner)
  3. HTML5 Best Practices: Table formatting via CSS3
  4. Edumatter-M12 for Windows, app overview
  5. Engineering Calculator VOLTA-814D
  6. CoolPhone: phone numbers-to-text converter
  7. SQL generates large data sequence
  8. Aggregate Product function extends SQL
  9. Top-50 Digital Cameras
  10. WebTV Project: Embedded YouTube Player (Goog #1 YouTube API for ASP.NET)
Dr. Bell is personally credited for 10+ Enterprise level projects (Finance/Investment, Engineering, Edu) w/total code base exceeding 250k lines; doing consulting in NYC for 20 yrs.
Follow on   Twitter

Comments and Discussions

 
GeneralReason for my vote of 5 Nice tip PinmemberWonde Tadesse11-Jun-11 13:44 
GeneralRe: Thanks a bunch! Have a great weekend! Best, Alex B. PinmemberDrABELL11-Jun-11 14:35 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 4 Jun 2013
Article Copyright 2011 by DrABELL
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid