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)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw