Tuesday, June 21, 2011

Make the entire GridView or any Table Row clickable and selectable in ASP.NET


Introduction

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

Demo

The fully functional demo of the embedded YouTube Video Player demonstrating the suggested technique is available at: http://webinfocentral.com/RESOURCES/WebTV.aspx (click on the image below to open the link)

YouTube Embedded Video

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>
Note: event-binding could be also done on the client side, for example, using jQuery .click() event. For mostly didactic purpose it's implemented here using C# and DataRowBound event to be consistent with core .NET technology set.

No comments:

Post a Comment