Click here to Skip to main content
15,891,684 members
Articles / Gridview

Gridview: Highlight Row/Cell using jQuery

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
22 Feb 2015CPOL2 min read 20.3K   3   1
In this article, I'm going to couple all types of "highlighting" rows/column using jQuery.

As an ASP.NET developer, every one experiences the most prominent Gridview. In this article, I'm going to couple all types of "highlighting" rows/column using jQuery.

Problem

You may need to achieve any one of the following:

  1. Highlight the row when mouse over on it in a grid view.

  2. Highlight the cell when mouse over on it:

  3. Highlight a row of the gridview when click on the row.

  4. Highlight a cell on a gridview when click on the cell.

Prerequisite

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

Code

As a first step, we need some data to be filled in Gridview. For this purpose, I have created a simple table "tblEmployee" with some columns.

SQL
CREATE TABLE [dbo].[tblEmployee](
	[EmpID] [int] NOT NULL,
	[EmpName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[EmpAge] [int] NOT NULL,
 CONSTRAINT [PK_tblEmp] PRIMARY KEY CLUSTERED 
(
	[EmpID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

Use the below script to insert values into that table:

SQL
insert into tblEmployee values (1,'Francis',30);
insert into tblEmployee values (2,'Ram',25);
insert into tblEmployee values (3,'Arul',25);
insert into tblEmployee values (4,'Prabhu',30);

As a next step, create a webform and include a gridview into it as below:

XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewDemo.aspx.cs" 
	Inherits="DemoWebApp.GridviewDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvEmployee" runat="server" 
		EmptyDataText="No Records Found" AutoGenerateColumns="false" >
                <Columns>
                    <asp:BoundField HeaderText="SNo" DataField="EmpID" />
                    <asp:BoundField HeaderText="Employee Name" DataField="EmpName" />
                    <asp:BoundField HeaderText="Age" DataField="EmpAge"  />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

The below code in the code-behind file is used to check the post-back and call the method to bind the data table to gridview.

C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // Bind the grid
        gvEmployee.DataSource = GetDataFromDB();
        gvEmployee.DataBind();
    }
}

The below function is used to get data from database and return a datatable.

C#
private DataTable GetDataFromDB()
    {
        DataTable dt = new DataTable();
        // Read Connection String from WebConfig
        string strConString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
        // Create connection object
        using (SqlConnection con = new SqlConnection(strConString))
        {
            string strQuery = "Select * from tblEmployee";
            // open connection
            con.Open();
            // create command object
            SqlCommand cmd = new SqlCommand(strQuery, con);
            // create adapter
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            // execute query and fill the data into datatable
            da.Fill(dt);
        }
        return dt;
    }

We are going to define the following "style" classes in the aspx file itself. These classes are going to be used in jQuery to highlight the row/cell.

XML
<style type="text/css">
        .selectedCell {
            background-color: lightblue;
        }

        .unselectedCell {
            background-color: white;
        }
    </style>

In the next step, I'm going to add the jQuery in the aspx file (between the <script>  and </script> tag). The below jQuery snippet is used to highlight the row when mouse over on it.

JavaScript
// Highlight the row when mouse over on it
$(document).ready(function () {
    $('#gvEmployee tr').hover(function () {
        $(this).addClass('selectedCell');
    }, function () { $(this).removeClass('selectedCell'); });
});

Include the below jQuery code if you want to highlight the cell instead of row:

JavaScript
// Highlight the cell when mouse over on it
$(document).ready(function () {
    $('#gvEmployee td').hover(function () {
        $(this).addClass('selectedCell');
    }, function () { $(this).removeClass('selectedCell'); });
});

The below jQuery is used to highlight the row when the particular row is clicked.

JavaScript
//Highlight the cell when the row clicked
$(function () {
    $(document).on('click', '#gvEmployee tr', function () {
        $("#gvEmployee tr").removeClass('selectCell');
        $(this).addClass('selectCell');
    });
});

Include the below jQuery code if you want to highlight the cell when the particular cell is clicked.

JavaScript
//Highlight the cell when the row clicked
$(function () {
    $(document).on('click', '#gvEmployee tr', function () {
        $("#gvEmployee tr").removeClass('selectCell');
        $(this).addClass('selectCell');
    });
});

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 "RowDataBound" event of Gridview. For example, I'm going to highlight the row based on the "age" column value.

C#
protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());
        if (age >= 25 && age < 30)
        {
            e.Row.BackColor = Color.GreenYellow;
        }
        if (age == 30)
        {
            e.Row.BackColor = Color.LightBlue;
        }
    }
}

The output looks like below:

Highlight Rows on Databound

In another way, you may want to highlight the column alone while binding the data, the below code accomplishes this.

C#
protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());
        if (age >= 25 && age < 30)
        {
            e.Row.Cells[2].BackColor = Color.GreenYellow;
        }
        if (age == 30)
        {
            e.Row.Cells[2].BackColor = Color.LightBlue;
        }
    }
}

The above code output is like below:

Highlight Column on Databound

If you need any clarifications, please let me know your thoughts as comments!

This article was originally posted at http://www.aspdotnetchamp.com

License

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


Written By
Software Developer (Senior)
India India
Hi All, I am Francis from India. Working as a Senior Software Engineer. I have 6+ Years of experience in ASP.Net and C#/VB.Net. Also founder of ASPDotNetChamp, where i blog my day to day ASP.Net Experiences, Problems and Interview Questions.

Comments and Discussions

 
QuestionselectCell Pin
laurie cote14-Nov-18 4:57
laurie cote14-Nov-18 4: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.