Click here to Skip to main content
13,353,124 members (64,822 online)
Click here to Skip to main content
Add your own
alternative version


29 bookmarked
Posted 7 Feb 2006

How to create the id of <td> and <tr> generated by DataGrid in ASP.NET and use it by client-side JavaScript.

, 7 Feb 2006
Rate this:
Please Sign up or sign in to vote.
How to create client-side id of table row and cell generated by a datagrid and the way to use it using javascript along with an example in C#.

Sample Image - mouseover.jpg


One of the main problems I faced while working with datagrid is that programmer has no hand in generating the id in the html of different controls of in the datagrid. Though there is a well formed logic behind the generated ClientID, but most of the times it is difficult to use from client-side Javascript.

For example if the id of datagrid is ItemsGrid and a checkbox with id chkSelect is in the first column of the data grid, then in the client side html the id of the checkboxes generated are like ‘ItemsGrid__ctl2_chkSelect’, ‘ItemsGrid__ctl3_chkSelect’ etc.

Moreover by default the datagrid generates a table without any id of the <td> and <tr> tags. So one cannot directly use client-side script to change the attributes of these <td> and <tr>, like changing the background color of a row on mouse hover.

This proved to be a real gotcha for me to integrate javascript with datagrid. I found that the ‘ClientID’ of the controls in datagrid to be very helpful and by adding the ‘attribute’ to the controls the problem can be solved. MSDN has given me a good hint to solve it.

Here is an example which shows how to change background color of the rows of the table generated by a datagrid in the javascript events ‘onmousemove’ and ‘onclick’ event of checkbox.

Sample screenshot

The HTML code for the datagrid is as follows:

<asp:datagrid id="ItemsGrid" runat="server" 


    BorderColor="Black" BorderWidth="1px" CellPadding="3" 

<AlternatingItemStyle BackColor="WhiteSmoke"></AlternatingItemStyle>
<HeaderStyle BackColor="LightGray"></HeaderStyle>
           <asp:CheckBox id="chkSelectAll" Runat="server" 

           <asp:CheckBox id="chkSelect" 

      <asp:BoundColumn DataField="FirstName" 

           HeaderText="First Name"></asp:BoundColumn>
      <asp:BoundColumn DataField="LastName" 

           HeaderText="Last Name"></asp:BoundColumn>
      <asp:BoundColumn DataField="Age" HeaderText="Age">
        <ItemStyle HorizontalAlign="Right"></ItemStyle>

The datagrid contains four columns, first one is ‘TemplateColumn’ with checkbox in it and the others are ‘BoundColumn’. The header of the ‘TemplateColumn’ also contains a checkbox ‘chkSelectAll’ which is used to select or deselect the other checkboxes.

The C# code snippet is give below:

private DataTable CreateDataSource()
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("FirstName", 
    dt.Columns.Add(new DataColumn("LastName", 
    dt.Columns.Add(new DataColumn("Age", typeof(int)));

    DataRow[] dr = new DataRow[5];
    dr[0] = dt.NewRow();
    dr[0][0] = "Pradipta";
    dr[0][1] = "Basu";
    dr[0][2] = "30";
    dr[1] = dt.NewRow();
    dr[1][0] = "Sanjoy";
    dr[1][1] = "Chatterjee";
    dr[1][2] = "31";
    dr[2] = dt.NewRow();
    dr[2][0] = "Arabinda";
    dr[2][1] = "Sen";
    dr[2][2] = "31";
    dr[3] = dt.NewRow();
    dr[3][0] = "Kuntal";
    dr[3][1] = "Ghoshal";
    dr[3][2] = "24";
    dr[4] = dt.NewRow();
    dr[4][0] = "Arijit";
    dr[4][1] = "Chowdhury";
    dr[4][2] = "25";

    return dt;

void Page_Load(Object sender, EventArgs e) 
    if (!IsPostBack) 
        // Load this data only once.
        ItemsGrid.DataSource = CreateDataSource();

private void ItemsGrid_ItemDataBound(object sender, 
                           DataGridItemEventArgs e)
    ListItemType itemType = (ListItemType)e.Item.ItemType;
    if ((itemType != ListItemType.Footer) && 
        (itemType != ListItemType.Separator))
        if(itemType == ListItemType.Header)
        //Add attributes to the <th>
        object checkBox = e.Item.FindControl("chkSelectAll");
        if(checkBox != null)
              "Javascript:chkSelectAll_OnClick(" + 
              ((CheckBox)checkBox).ClientID + ")");
            // Add attributes to the <td>.
            string tableRowId = ItemsGrid.ClientID + "_row" + 
            e.Item.Attributes.Add("id", tableRowId);
            object checkBox = e.Item.FindControl("chkSelect");
            if(checkBox != null)
                string clientId = ((CheckBox)checkBox).ClientID;
                   "Javascript:chkSelect_OnMouseMove(" + 
                   tableRowId + "," + clientId + ")");
                   "Javascript:chkSelect_OnMouseOut(" + 
                   tableRowId + "," + clientId + "," + 
                   e.Item.ItemIndex + ")");
                   "Javascript:chkSelect_OnClick(" + 
                   tableRowId + "," + clientId + "," + 
                   e.Item.ItemIndex + ")");

In Page_Load() the datasource of the Datagrid is set and data binding is done. The function ‘CreateDataSource()’ creates a DataTable for the Datagrid to use.

In ItemDataBound event handler, I have done the following :

  • the id of each row is set. The id is generated by concatenating the ClientId of the datagrid with a string ‘row’ and the ItemIndex. The ClientID of the datagrid is used since the client side id of the datagrid gets changed if the datagrid is used inside a usercontrol.
  • OnMouseMove and OnMouseOut javascript events are set
  • OnClick event of all the checkboxes including the checkbox in the header is set.

The javascript used in the code are as follows:

function chkSelect_OnMouseMove(tableRowId, checkBox)
    if(checkBox.checked == false) = "#ffffcc";

function chkSelect_OnMouseOut(tableRowId, 
                      checkBox, rowIndex)
    if(checkBox.checked == false)
        var bgColor;
        if(rowIndex%2 == 0)
            bgColor = "#ffffff";
            bgColor = "#f5f5f5"; = bgColor;

function chkSelect_OnClick(tableRowId, 
                   checkBox, rowIndex)
    var bgColor;
    if(rowIndex%2 == 0)
        bgColor = "#ffffff";
        bgColor = "#f5f5f5";
    if(checkBox.checked == true) = "#b0c4de";
    else = bgColor;

function chkSelectAll_OnClick(checkBox)
    re = new RegExp('_chkSelect$')
    for(i = 0; i < 
         document.forms[0].elements.length; i++) 
        elm = document.forms[0].elements[i]
        if (elm.type == 'checkbox') 
            if (re.test( 
                elm.checked = checkBox.checked;
                var tableId =;
                var rowIndex = 
                   tableId.substring(tableId.length - 1, 
                   elm, rowIndex);

The function chkSelect_OnMouseMove() changes the background color of the row over which the mouse is moved. It checks whether the checkbox in the row is checked or not. If the checkbox is not checked, then it changes the background color.

The function chkSelect_OnMouseOut() restores the background color of the row to its original when the mouse moves out of a row.

The function chkSelect_OnClick() also changes the background color of the corresponding row when the checkbox in the row is selected and restores the original color when the checkbox is deselected.

Note: While setting the color to original color, it is checked that the row number is even or odd, since AlternatingItemStyle-BackColor property of the datagrid is used, to make things a bit complicated.

The function chkSelectAll_OnClick() is fired when the checkbox ‘chkSelectAll’ in the header of the datagrid is checked or unchecked. When this checkbox is checked or unchecked, then all the checkboxes in each row is also checked or unchecked accordingly with corresponding changes in background color of rows in the table.

The code is tested for IE 6.0, Mozilla Firefox 1.0.7 and Opera 8.5

The included solution and project contains the full source code for the example.

Thank you for reading my code.


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


About the Author

Pradipta Basu
Web Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralWon't convert to VS2008 Pin
rmagro6-Mar-09 1:58
memberrmagro6-Mar-09 1:58 
QuestionHow to add CSS format to this code? Pin
Tony Dong13-Jun-06 21:29
memberTony Dong13-Jun-06 21:29 
AnswerRe: How to add CSS format to this code? Pin
Pradipta Basu15-Jun-06 1:13
memberPradipta Basu15-Jun-06 1:13 
GeneralRe: How to add CSS format to this code? Pin
Tony Dong15-Jun-06 7:34
memberTony Dong15-Jun-06 7:34 
GeneralGood Jobe Done!!! Pin
Arabinda Debika14-Feb-06 22:13
memberArabinda Debika14-Feb-06 22:13 
GeneralRe: Good Jobe Done!!! Pin
Jonathan Wilkes3-Jan-07 0:44
memberJonathan Wilkes3-Jan-07 0:44 
GeneralAlternative method to set id for table row by DataKeyField Pin
askant7-Feb-06 18:49
memberaskant7-Feb-06 18:49 
GeneralRe: Alternative method to set id for table row by DataKeyField Pin
Pradipta Basu11-Feb-06 9:57
memberPradipta Basu11-Feb-06 9:57 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 7 Feb 2006
Article Copyright 2006 by Pradipta Basu
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid