GridView: Highlight Row or Cell

Every ASP.Net developer experiences the most prominent GridView. This article shows all the many types of "highlighting" of rows/columns of a GridView using jQuery.
 
Problem

You may need to do any one of the following.

1. Highlight the row when the mouse is over it in a GridView.

 
 2. Highlight the cell when the mouse is over it.

 3. Highlight a row of the GridView when a row is clicked.

 
 4. Highlight a cell on a GridView when clicked.

 
Prerequisite

This tutorial relies on jQuery purely. So you need to include the jQuery library in your solution. You can download jQuery from here.

Code

As a first step, we need some data to be filled into the GridView. For this purpose, I have created a simple table "tblEmployee" with some columns.
  1. CREATE TABLE [dbo].[tblEmployee](  
  2.     [EmpID] [intNOT NULL,  
  3.     [EmpName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,  
  4.     [EmpAge] [intNOT NULL,  
  5.  CONSTRAINT [PK_tblEmp] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [EmpID] ASC  
  8. )WITH (IGNORE_DUP_KEY = OFFON [PRIMARY]  
  9.   
  10. ON [PRIMARY
Use the following script to insert values into that table:
  1. insert into tblEmployee values (1,'Francis',30);  
  2. insert into tblEmployee values (2,'Ram',25);  
  3. insert into tblEmployee values (3,'Arul',25);  
  4. insert into tblEmployee values (4,'Prabhu',30); 
As a next step, create a webform and include a GridView into it as in the following:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewDemo.aspx.cs" Inherits="DemoWebApp.GridviewDemo" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.         <div>  
  10.             <asp:GridView ID="gvEmployee" runat="server" EmptyDataText="No Records Found" AutoGenerateColumns="false" >  
  11.                 <Columns>  
  12.                     <asp:BoundField HeaderText="SNo" DataField="EmpID" />  
  13.                     <asp:BoundField HeaderText="Employee Name" DataField="EmpName" />  
  14.                     <asp:BoundField HeaderText="Age" DataField="EmpAge"  />  
  15.                 </Columns>  
  16.             </asp:GridView>  
  17.         </div>  
  18.     </form>  
  19. </body>  
  20. </html> 
The following code in the code-behind file checks the post-back and calls the method to bind the datatable to the GridView.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!Page.IsPostBack)  
  4.     {  
  5.         // Bind the grid  
  6.         gvEmployee.DataSource = GetDataFromDB();  
  7.         gvEmployee.DataBind();  
  8.     }  

The following function is used to get data from the database and return a datatable.
  1. private DataTable GetDataFromDB()    
  2. {    
  3.     DataTable dt = new DataTable();    
  4.     // Read Connection String from WebConfig    
  5.     string strConString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();    
  6.     // Create connection object    
  7.     using (SqlConnection con = new SqlConnection(strConString))    
  8.     {    
  9.         string strQuery = "Select * from tblEmployee";    
  10.         // open connection    
  11.         con.Open();    
  12.         // create command object    
  13.         SqlCommand cmd = new SqlCommand(strQuery, con);    
  14.         // create adapter     
  15.         SqlDataAdapter da = new SqlDataAdapter(cmd);    
  16.         // execute query and fill the data into datatable    
  17.         da.Fill(dt);    
  18.     }    
  19.     return dt;    
  20. }  
We will define the following "style" classes in the aspx file itself. These classes will be used in jQuery to highlight the row/cell. 
  1. <style type="text/css">  
  2.     .selectedCell {  
  3.         background-color: lightblue;  
  4.     }  
  5.         .unselectedCell {  
  6.         background-colorwhite;  
  7.     }  
  8. </style> 
In the next step I'm going to add the jQuery to the aspx file (between the <script> and </script> tags). The following jQuery snippet is used to highlight the row when the mouse is over it.
  1. // Highlight the row when mouse over on it  
  2. $(document).ready(function () {  
  3.     $('#gvEmployee tr').hover(function () {  
  4.         $(this).addClass('selectedCell');  
  5.     }, function () { $(this).removeClass('selectedCell'); });  
  6. }); 
Include the following jQuery code if you want to highlight the cell instead of row:
  1. // Highlight the cell when mouse over on it  
  2.  $(document).ready(function () {  
  3.      $('#gvEmployee td').hover(function () {  
  4.          $(this).addClass('selectedCell');  
  5.      }, function () { $(this).removeClass('selectedCell'); });  
  6. }); 
The following jQuery is used to highlight the row when the specific row is clicked.
  1. //Highlight the cell when the row clicked  
  2. $(function () {  
  3.     $(document).on('click''#gvEmployee tr'function () {  
  4.         $("#gvEmployee tr").removeClass('selectCell');  
  5.         $(this).addClass('selectCell');  
  6.     });  
  7. }); 
Include the following jQuery code if you want to highlight the cell when the specific cell is clicked.
  1. //Highlight the cell when the row clicked  
  2.  $(function () {  
  3.      $(document).on('click''#gvEmployee tr'function () {  
  4.          $("#gvEmployee tr").removeClass('selectCell');  
  5.          $(this).addClass('selectCell');  
  6.      });  
  7.  }); 
Highlight row/cell based on some condition:

In some cases you may want to highlight the row or cells based on some condition too. In that case, you can use the "RowDataBound" event of GridView. As an example I will highlight the row based on the "age" column value.
  1. protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)  
  2. {  
  3.     if (e.Row.RowType == DataControlRowType.DataRow)  
  4.     {  
  5.         int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());  
  6.         if (age >= 25 && age < 30)  
  7.         {  
  8.             e.Row.BackColor = Color.GreenYellow;  
  9.         }  
  10.         if (age == 30)  
  11.         {  
  12.             e.Row.BackColor = Color.LightBlue;  
  13.         }  
  14.     }  

The output will look as in the following:

 
In another way, you may want to highlight the column alone when binding the data, the following code does that.
  1. protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)  
  2. {  
  3.     if (e.Row.RowType == DataControlRowType.DataRow)  
  4.     {  
  5.         int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());  
  6.         if (age >= 25 && age < 30)  
  7.         {  
  8.             e.Row.Cells[2].BackColor = Color.GreenYellow;  
  9.         }  
  10.         if (age == 30)  
  11.         {  
  12.             e.Row.Cells[2].BackColor = Color.LightBlue;  
  13.         }  
  14.     }  

 The above code output will be as in the following: