Sunday, April 24, 2016

How to change color in Grid View based on a condition?

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. 
01CREATE TABLE Employee
02(
03Id INT IDENTITY PRIMARY KEY,
04EmployeeName VARCHAR(100),
05Department VARCHAR(100),
06Designation VARCHAR(100),
07JoinedDate DATE,
08Salary INT
09)
10GO
11
12INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
13VALUES('Employee-1','Development','Trainee','2009-06-01','10000')
14
15INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
16VALUES('Employee-2','Design','Web Developer','2014-06-01','20000')
17
18INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
19VALUES('Employee-3','Testing','Junior Tester','2011-06-01','35000')
20
21INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
22VALUES('Employee-4','Product','Senior Manager','2012-06-01','50000')
23
24INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
25VALUES('Employee-5','Development','Tech Lead','2005-06-01','49000')
26
27INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
28VALUES('Employee-6','Development','Pjoject Manager','2009-06-01','70000')
29
30INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
31VALUES('Employee-7','Design','Web Developer','2014-06-01','20000')
32
33INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
34VALUES('Employee-8','Testing','Junior Tester','2011-06-01','54000')
35
36INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
37VALUES('Employee-9','Product','Senior Manager','2012-06-01','35000')
38
39INSERT INTO Employee(EmployeeName,Department,Designation,JoinedDate,Salary)
40VALUES('Employee-10','Development','Tech Lead','2005-06-01','55000')
41GO
42
43CREATE PROC GetEmployeeDetails
44AS
45BEGIN
46SET NOCOUNT ON
47SELECT FROM Employee
48SET NOCOUNT OFF
49END
50GO

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. 
1<form id="form1" runat="server">
2<div>
3<h2>
4Change Row Color Based On Condition</h2>
5<asp:gridview autogeneratecolumns="true" id="grdResults" runat="server">
6        </asp:gridview>
7    </div>
8</form>

Now before proceeding further to write the cs code add connection string in web.config file 
1<connectionstrings>
2  <add connectionstring="Data Source=local; Initial Catalog=mydb; User ID=SA;password=mypassword;" name="mydsn">
3</add></connectionstrings>

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

VB.Net: 
1Imports System.Data
2Imports System.Data.SqlClient
3Imports 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: 
01protected void Page_Load(object sender, EventArgs e)
02{
03    try
04    {
05        //read connection string from web.config
06        string connectionString = ConfigurationManager.ConnectionStrings["mydsn"].ConnectionString;
07        using (SqlConnection conn = new SqlConnection(connectionString))
08        {
09            using (SqlCommand cmd = new SqlCommand())
10            {
11                //Setting connection and command text to command object
12                cmd.Connection = conn;
13                cmd.CommandText = "GetEmployeeDetails";
14                cmd.CommandType = CommandType.StoredProcedure;
15
16                //Filling dataset with data
17                DataSet customers = new DataSet();
18                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
19                adapter.Fill(customers, "EmployeeDetails");
20                     
21                //Binding grid view
22                grdResults.DataSource = customers.Tables["EmployeeDetails"];
23                grdResults.DataBind();
24            }
25        }
26    }
27    catch (Exception ex)
28    {
29        // handle error
30    }
31}

VB.Net:
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 Try
03  'read connection string from web.config
04  Dim connectionString As String = ConfigurationManager.ConnectionStrings("mydsn").ConnectionString
05  Using conn As New SqlConnection(connectionString)
06   Using cmd As New SqlCommand()
07    'Setting connection and command text to command object
08    cmd.Connection = conn
09    cmd.CommandText = "GetEmployeeDetails"
10    cmd.CommandType = CommandType.StoredProcedure
11
12    'Filling dataset with data
13    Dim customers As New DataSet()
14    Dim adapter As New SqlDataAdapter(cmd)
15    adapter.Fill(customers, "EmployeeDetails")
16
17    'Binding grid view
18    grdResults.DataSource = customers.Tables("EmployeeDetails")
19    grdResults.DataBind()
20   End Using
21  End Using
22   ' handle error
23 Catch ex As Exception
24 End Try
25End 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: 
01protected void grdProduct_RowDataBound(object sender, GridViewRowEventArgs e)
02{
03    if (e.Row.RowType == DataControlRowType.DataRow)
04    {
05        //Getting salary of each employee
06        int Salary=  int.Parse(e.Row.Cells[5].Text);
07        if (Salary > 50000)
08        {
09            //Setting row back colour
10            e.Row.BackColor = System.Drawing.Color.LightGreen;
11        }
12        else if (Salary < 20000)
13        {
14            e.Row.BackColor = System.Drawing.Color.Pink;
15        }
16    }
17}

VB.Net: 
01Protected Sub grdProduct_RowDataBound(sender As Object, e As GridViewRowEventArgs)
02 If e.Row.RowType = DataControlRowType.DataRow Then
03  'Getting salary of each employee
04  Dim Salary As Integer Integer.Parse(e.Row.Cells(5).Text)
05  If Salary > 50000 Then
06   'Setting row back colour
07   e.Row.BackColor = System.Drawing.Color.LightGreen
08  ElseIf Salary < 20000 Then
09   e.Row.BackColor = System.Drawing.Color.Pink
10  End If
11 End If
12End 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
 Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work, you can appreciate by leaving your comments. Stay tuned and stay connected for more technical updates."

No comments:

Post a Comment