Skip to main content

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

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:

Comments

  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

Post a Comment

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...