Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Change the GridView row color on click without postback

4.17/5 (17 votes)
18 Mar 2008CPOL 1   1.2K  
Article about changing the GridView row color on mouse click without postback

Introduction

This article is about changing the color of a GridView row on mouse click without having a postback on the page. In order to achieve this we will be using some javascript and off course the GridView Control itself :).

Background

GridView is a server side control that contains Rows and Columns. In some cases we want to do something more than the straight forward functionality of the GridView control depending on the functional/UI requirements of the application.

Using the code

Following javascript will be used to change the color of the row.

JavaScript
   <script type="text/javascript">
   //variable that will store the id of the last clicked row
   var previousRow;

   function ChangeRowColor(row)
   {
       //If last clicked row and the current clicked row are same
       if (previousRow == row)
           return;//do nothing
       //If there is row clicked earlier
       else if (previousRow != null)
           //change the color of the previous row back to white
           document.getElementById(previousRow).style.backgroundColor = "#ffffff";

       //change the color of the current row to light yellow

       document.getElementById(row).style.backgroundColor = "#ffffda";
       //assign the current row id to the previous row id
       //for next row to be clicked
       previousRow = row;
   }
</script>

Following code will be required on GridView1_RowDataBound event

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
    Handles GridView1.RowDataBound
    If (e.Row.RowType = DataControlRowType.DataRow) Then
        e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor('" & e.Row.ClientID & "')")
    End If
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        'FillDataTable is a function that will return a DataTable
        'with some values and is available in the code for download.
        Me.GridView1.DataSource = Me.FillDataTable()
        Me.GridView1.DataBind()
    End If
End Sub

Before clicking the row

After clicking the row

License

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