Change or highlight Asp.net GridView cell background color based on condition

Highlight or change asp.net GridView Cell background and Text color based on condition
Click on image to enlarge
Introduction: In this article i am going to share the code example to highlight or change cell/column background and text color in GridView Data control based on some condition in asp.net using both C# and VB languages.

Basically you will learn the following through this article: 
  • How to Save data using stored procedures in Sql server database and bind the data from sql server database to GridView data control.
  • How to conditionally highlight cell background and text color in GridView.
  • How to find asp.net control inside GridView e.g. we will find the Label control placed inside Grid view displaying gender value and assign color to it.

Description: Sometimes we want to highlight some data in GridView so that we can clearly differentiate some data against the large number of records being displayed in GridView. There may be multiple occasions where we need to change the cell color of GridView to make it different and easily identifiable
For example: if we are displaying the details of all the students and we want to differentiate the students based on their gender i.e. By male or female then we can assign different colors to all the students based on their gender. I am going to implement this in this article.

Implementation:  Let's create a demo website to demonstrate the concept.
  • First of all create a DataBase in Sql server and name it e.g.  "DB_Student" and in this database create a table with the following Columns and Data type as shown below and name this table "Tbl_Student".
  
Column Name
Data Type
StudentId
Int(Primary Key. So set is identity=true)
StudentName
varchar(100)
Class
varchar(50)
Age
Int
Gender
varchar(50)
Address
varchar(500)

  • Create a stored procedure to save student details in sql server database table

 CREATE PROCEDURE SaveStudentDetails_SP
                @StudentName                               VARCHAR(100),
                @Class                                                 VARCHAR(50),
                @Age                                                    INT,
                @Gender                                             VARCHAR(10),
                @Address                                           VARCHAR(500)
AS
BEGIN
                INSERT INTO dbo.Tbl_Student(StudentName,Class,Age,Gender,Address)
                VALUES(@StudentName,@Class,@Age,@Gender,@Address)
END

  • Create another stored procedure to get student details to be filled in GridView Data Control.

 CREATE PROCEDURE GetStudentDetails_SP               
AS
BEGIN
                SELECT * FROM dbo.Tbl_Student
END

  • Now let's connect our asp.net application with Sql Server database

So In the <configuration> tag of  web.config file create the connection string as:
  
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=DB_Student;Integrated Security=True"/>
  </connectionStrings>

Note:  Replace the Data Source and Initial Catalog as per your database settings.

  • In the <Form> tag of the asp.net design page (e.g. Default.aspx) design the page as:

<div>
    <fieldset style="width:370px;">
    <legend>Highlight Gridview cell/column based on condition</legend>
    <table>
    <tr>
    <td>Student Name:</td>
    <td>
        <asp:TextBox ID="txtStuName" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Class:</td>
    <td>
        <asp:TextBox ID="txtClass" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>       
    </tr>
    <tr>
    <td>Gender:</td>
    <td>
        <asp:RadioButtonList ID="rblGender" RepeatColumns="2" RepeatDirection="Horizontal" runat="server">
        <asp:ListItem>Male</asp:ListItem>
        <asp:ListItem>Female</asp:ListItem>
        </asp:RadioButtonList>
        </td>
    </tr>
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>
        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
        <asp:Button ID="btnReset" runat="server" Text="Reset"
            onclick="btnReset_Click" />
        </td>
    </tr>

    <tr>
    <td colspan="2">
        <asp:GridView ID="grdStudentDetails" runat="server" AutoGenerateColumns="False"
            onrowdatabound="grdStudentDetails_RowDataBound">
        <Columns>
        <asp:BoundField HeaderText="Student Name"  DataField="StudentName" />
        <asp:BoundField HeaderText="Class"  DataField="Class" />
        <asp:BoundField HeaderText="Age"  DataField="Age" />
        <asp:BoundField HeaderText="Gender"  DataField="Gender" />
        <asp:BoundField HeaderText="Address"  DataField="Address" />       
        </Columns>
        </asp:GridView>   
    </td>
    </tr>
    </table>
    </fieldset>
    </div>

Note if you are using BoundField to display data in GridView as Highlighted above in Yellow Color then you need to write the following code in RowDataBoundEvent of gridview:

    protected void grdStudentDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!string.IsNullOrEmpty(e.Row.Cells[3].Text))
            {
                if (e.Row.Cells[3].Text == "Male")
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Cyan;
                }
                else
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Orange;
                }
            }
    }
   
But if you are using Template Field and Item template to display data .e.g. as shown below highlighted in yellow color

<asp:GridView ID="grdStudentDetails" runat="server" AutoGenerateColumns="False"
            onrowdatabound="grdStudentDetails_RowDataBound">
        <Columns>
      
        <asp:TemplateField HeaderText="Student Name">
        <ItemTemplate>
        <asp:Label ID="lblStudentname" runat="server" Text='<%#Eval("StudentName") %>'></asp:Label>      
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Class">
        <ItemTemplate>      
        <asp:Label ID="lblClass" runat="server" Text='<%#Eval("Class") %>'></asp:Label>      
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Age">
        <ItemTemplate>       
        <asp:Label ID="lblAge" runat="server" Text='<%#Eval("Age") %>'></asp:Label>       
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Gender">
        <ItemTemplate>       
        <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>       
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
        <ItemTemplate>       
        <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>

Then you need to write the following code to find the label control displaying gender value and assign color to the row accordingly in RowDataBound control as:

protected void grdStudentDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblGender = (Label)e.Row.FindControl("lblGender");

            if (!string.IsNullOrEmpty(lblGender.Text))
            {
                if (lblGender.Text == "Male")
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Cyan;
                }
                else
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Orange;
                }
            }
        }      
    }

So the complete code would be as:

Asp.Net C# Section:
  • In code behind file (default.aspx.cs) write the code as;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
  
public partial class default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGridView();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd = new SqlCommand("SaveStudentDetails_SP", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StudentName", txtStuName.Text.Trim());
            cmd.Parameters.AddWithValue("@Class", txtClass.Text.Trim());
            cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim());
            if (rblGender.SelectedIndex == 0) //male
            {
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text);
            }
            else //Female
            {
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text);
            }
           
            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            Clear_Controls();
            BindGridView();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Oops!! Error occured: " + ex.Message.ToString() + "');"true);
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

    private void BindGridView()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            adp = new SqlDataAdapter("GetStudentDetails_SP", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdStudentDetails.DataSource = dt;
                grdStudentDetails.DataBind();
            }
            else
            {
                grdStudentDetails.DataSource = null;
                grdStudentDetails.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Oops!! Error occured: " + ex.Message.ToString() + "');"true);
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }
  
    protected void grdStudentDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    { 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!string.IsNullOrEmpty(e.Row.Cells[3].Text))
            {
                if (e.Row.Cells[3].Text == "Male")
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Cyan;
                }
                else
                {
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].BackColor = System.Drawing.Color.Orange;
                }
            }
        }

//If you are using Template field instead of BoundField then uncomment below code block and comment or remove above code block
  
//if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    Label lblGender = (Label)e.Row.FindControl("lblGender");

        //    if (!string.IsNullOrEmpty(lblGender.Text))
        //    {
        //        if (lblGender.Text == "Male")
        //        {
        //            e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
        //            e.Row.Cells[3].BackColor = System.Drawing.Color.Cyan;
        //        }
        //        else
        //        {
        //            e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;
        //            e.Row.Cells[3].BackColor = System.Drawing.Color.Orange;
        //        }
        //    }
        //}      
    }

  protected void btnReset_Click(object sender, EventArgs e)
    {
        Clear_Controls();
    }

    private void Clear_Controls()
    {
        txtStuName.Text = string.Empty;
        txtClass.Text = string.Empty;
        txtAge.Text = string.Empty;
        rblGender.ClearSelection();
        txtAddress.Text = string.Empty;
        txtStuName.Focus();
    }   
}

Asp.Net VB Section:

  • Design the page (default.aspx) as  in above Asp.net C#  section but replace the lines

<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" onclick="btnReset_Click" />
with the following lines
<asp:Button ID="btnSave" runat="server" Text="Save"/>
<asp:Button ID="btnReset" runat="server" Text="Reset" />

  •  In the code behind file(e.g. default.aspx.vb) write the code as:

 Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load
        If Not Page.IsPostBack Then
            BindGridView()
        End If
    End Sub

    Protected Sub btnSave_Click(sender As Object, e As System.EventArgsHandles btnSave.Click
        Dim cmd As New SqlCommand()
        Try
            cmd = New SqlCommand("SaveStudentDetails_SP", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@StudentName", txtStuName.Text.Trim())
            cmd.Parameters.AddWithValue("@Class", txtClass.Text.Trim())
            cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim())
            If rblGender.SelectedIndex = 0 Then
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text)
            Else
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text)
            End If

            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Clear_Controls()
            BindGridView()
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Oops!! Error occured: " & ex.Message.ToString() & "');"True)
        Finally
            cmd.Dispose()
            con.Close()
            con.Dispose()
        End Try
    End Sub

    Private Sub BindGridView()
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter()
        Try
            adp = New SqlDataAdapter("GetStudentDetails_SP", con)
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                grdStudentDetails.DataSource = dt
                grdStudentDetails.DataBind()
            Else
                grdStudentDetails.DataSource = Nothing
                grdStudentDetails.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Oops!! Error occured: " & ex.Message.ToString() & "');"True)
        Finally
            con.Close()
            dt.Clear()
            dt.Dispose()
            adp.Dispose()
        End Try
    End Sub

   
    Protected Sub grdStudentDetails_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgsHandles grdStudentDetails.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If Not String.IsNullOrEmpty(e.Row.Cells(3).Text) Then
                If e.Row.Cells(3).Text = "Male" Then
                    e.Row.Cells(3).ForeColor = System.Drawing.Color.Black
                    e.Row.Cells(3).BackColor = System.Drawing.Color.Cyan
                Else
                    e.Row.Cells(3).ForeColor = System.Drawing.Color.Black
                    e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
                End If
            End If
        End If


        'If e.Row.RowType = DataControlRowType.DataRow Then
        '    Dim lblGender As Label = DirectCast(e.Row.FindControl("lblGender"), Label)

        '    If Not String.IsNullOrEmpty(lblGender.Text) Then
        '        If lblGender.Text = "Male" Then
        '            e.Row.Cells(3).ForeColor = System.Drawing.Color.Black
        '            e.Row.Cells(3).BackColor = System.Drawing.Color.Cyan
        '        Else
        '            e.Row.Cells(3).ForeColor = System.Drawing.Color.Black
        '            e.Row.Cells(3).BackColor = System.Drawing.Color.Orange
        '        End If
        '    End If
        'End If
    End Sub

    Protected Sub btnReset_Click(sender As Object, e As System.EventArgsHandles btnReset.Click
        Clear_Controls()
    End Sub

    Private Sub Clear_Controls()
        txtStuName.Text = String.Empty
        txtClass.Text = String.Empty
        txtAge.Text = String.Empty
        rblGender.ClearSelection()
        txtAddress.Text = String.Empty
        txtStuName.Focus()
    End Sub 
End Class

Now over to you:
" I hope you have got the way to change the row color or we can say change GridView cell and text color conditionally  in Asp.Net and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 
Previous
Next Post »

1 comments:

Click here for comments
lingmaaki
admin
September 30, 2014 ×

A complete tutorial on...Asp.Net Gridview Tutorial

Ling

Congrats bro lingmaaki you got PERTAMAX...! hehehehe...
Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..