Change Row Color of a Grid view Based on Particular Condition C#.Net ASP.Net VB.Net

By
Advertisement
In this article i am going to explain about how to change the row color of a particular row in grid view based on the particular condition to differentiate the rows. For explanation purpose i have created a table called Employee in my local database and inserted 10 sample records. And also i have created a procedure called GetEmployeeDetails which will return all the details of the employee tables. below is the sql script used.
CREATE TABLE Employee
(
Id INT IDENTITY PRIMARY KEY,
EmployeeName VARCHAR(100),
Department VARCHAR(100),
Designation VARCHAR(100),
JoinedDate DATE,
Salary INT
)
GO

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-1','Development','Trainee','2009-06-01','10000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-2','Design','Web Developer','2014-06-01','20000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-3','Testing','Junior Tester','2011-06-01','35000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-4','Product','Senior Manager','2012-06-01','50000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-5','Development','Tech Lead','2005-06-01','49000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-6','Development','Pjoject Manager','2009-06-01','70000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-7','Design','Web Developer','2014-06-01','20000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-8','Testing','Junior Tester','2011-06-01','54000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-9','Product','Senior Manager','2012-06-01','35000')

INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
VALUES('Employee-10','Development','Tech Lead','2005-06-01','55000')
GO

CREATE PROC GetEmployeeDetails
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM Employee
SET NOCOUNT OFF
END
GO

Now create a new asp.net application and drog and drop the grid view control on your form. And set AutoGenerateColumns property to true(By default it is true. You no need to do it.) That is it. Below is the html markup of the code.

Change Row Color Based On Condition


Now before proceeding further to write the cs code add connection string in web.config file

  


And now include the below namespaces in your code file.
C#.Net:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

And in page load write the code to fetch the data from your table and bind it to grid view. The code is given below.
C#.Net:
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //read connection string from web.config
        string connectionString = ConfigurationManager.ConnectionStrings["mydsn"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                //Setting connection and command text to command object
                cmd.Connection = conn;
                cmd.CommandText = "GetEmployeeDetails";
                cmd.CommandType = CommandType.StoredProcedure;

                //Filling dataset with data
                DataSet customers = new DataSet();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(customers, "EmployeeDetails");
                    
                //Binding grid view
                grdResults.DataSource = customers.Tables["EmployeeDetails"];
                grdResults.DataBind();
            }
        }
    }
    catch (Exception ex)
    {
        // handle error
    }
}

VB.Net:
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Try
  'read connection string from web.config
  Dim connectionString As String = ConfigurationManager.ConnectionStrings("mydsn").ConnectionString
  Using conn As New SqlConnection(connectionString)
   Using cmd As New SqlCommand()
    'Setting connection and command text to command object
    cmd.Connection = conn
    cmd.CommandText = "GetEmployeeDetails"
    cmd.CommandType = CommandType.StoredProcedure

    'Filling dataset with data
    Dim customers As New DataSet()
    Dim adapter As New SqlDataAdapter(cmd)
    adapter.Fill(customers, "EmployeeDetails")

    'Binding grid view
    grdResults.DataSource = customers.Tables("EmployeeDetails")
    grdResults.DataBind()
   End Using
  End Using
   ' handle error
 Catch ex As Exception
 End Try
End Sub

Now if you run the code you will get the output as given below...
How To Change Row Color of a Particular Row in grid view Based on Particular Condition
But in my case i would like to differentiate the row based on the employee salary. For that one i added the OnRowDataBound="grdProduct_RowDataBound" event of the grid view. The event handler code is given below.
C#.Net:
protected void grdProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Getting salary of each employee
        int Salary=  int.Parse(e.Row.Cells[5].Text);
        if (Salary > 50000)
        {
            //Setting row back colour
            e.Row.BackColor = System.Drawing.Color.LightGreen;
        }
        else if (Salary < 20000)
        {
            e.Row.BackColor = System.Drawing.Color.Pink;
        }
    }
}

VB.Net:
Protected Sub grdProduct_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.DataRow Then
  'Getting salary of each employee
  Dim Salary As Integer = Integer.Parse(e.Row.Cells(5).Text)
  If Salary > 50000 Then
   'Setting row back colour
   e.Row.BackColor = System.Drawing.Color.LightGreen
  ElseIf Salary < 20000 Then
   e.Row.BackColor = System.Drawing.Color.Pink
  End If
 End If
End Sub

Now if you will get the below output.
How To Change Row Color of a Particular Row in grid view Based on Particular Condition
 Download Source:

1 comment:

  1. i tried, but result: rows were not highlighted.
    Besides, on Page_Load event handler we have GridView named "grdResults", and on other handler "grdProduct"

    ReplyDelete

Online Casino