How to Change Asp.Net GridView Cell Row and Column color based on condition in C# VB.Net

For data representation Asp.Net GridView Control undoubtedly popular. For making reports more often we use GridView Control. For indication or to attract user on some data we need to change Data forecolor or background color. Here in this article I will explain “How to Change Asp.Net GridView Cell Row and Column color based on condition in C# VB.Net“. To do this conditional formatting we need to use GridView RowDataBound. Because GridView RowDataBound event will fire while we bind data into the GridView. So to color GridView Cell, Row or even column we can use this event efficiently.

How to Change Asp.Net GridView Cell Row and Column color based on condition in C# VB.Net

To Do the Example First Create a Database Table:

CREATE TABLE [dbo].[tblStock](
    [BrandName] [varchar](max) NULL,
    [CategoryName] [varchar](max) NULL,
    [ProductName] [varchar](max) NULL,
    [LogicalQuantity] [bigint] NULL,
    [PhysicalQuantity] [bigint] NULL,
    [QuarentineQuantity] [bigint] NULL

Insert Some Data to Test:

INSERT INTO tblStock VALUES('Kohinoor','Soap','Tibbet Handwash',55781,55780,1)
INSERT INTO tblStock VALUES('Kohinoor','Soap','Tibbet Soap',38786,38780,6)
INSERT INTO tblStock VALUES('Kohinoor','ToothPaste','Tibbet Clear',34503,34500,3)
INSERT INTO tblStock VALUES('Proctor & Gamble','Bubble','',43809,43800,9)
INSERT INTO tblStock VALUES('Telenor','Mobile','Data SIM',43876,43870,6)
INSERT INTO tblStock VALUES('Telenor','Mobile','GP Modem',23907,23900,7)
INSERT INTO tblStock VALUES('Uniliver','Soap','Lux',19806,19800,6)
INSERT INTO tblStock VALUES('Uniliver','TeleProducts','Brittle',20703,20700,3)
INSERT INTO tblStock VALUES('Uniliver','ToothPaste','Close Up',16755,16750,5)

Now Modify the Web.Config File to Connect to Database:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now Prepare the GridView Control:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" 
        HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" 
        HeaderStyle-ForeColor="White" CellPadding="5" 
        onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="false">
        <asp:BoundField HeaderText="Brand Name" DataField="BrandName" />
        <asp:BoundField HeaderText="Category Name" DataField="CategoryName" />
        <asp:BoundField HeaderText="Product Name" DataField="ProductName" />
        <asp:BoundField HeaderText="Logical Qty" DataField="LogicalQuantity" />
        <asp:BoundField HeaderText="Physical Qty" DataField="PhysicalQuantity" />
        <asp:BoundField HeaderText="Quarentine Qty" DataField="QuarentineQuantity" />

Now Add Below Namespaces:
1. System.Data
2. System.Data.SqlClient
3. System.Configuration

Now Bind the GridView First:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            string consString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(consString))
                SqlCommand cmd = new SqlCommand("SELECT * FROM [tblStock]", conn);
                cmd.CommandType = CommandType.Text;
                SqlDataReader drStudents = cmd.ExecuteReader();
                GridView1.DataSource = drStudents;
                //Colouring GridView Column
                //GridView1.Columns[5].ItemStyle.BackColor = System.Drawing.Color.Violet;

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim consString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Using conn As New SqlConnection(consString)
                Dim cmd As New SqlCommand("SELECT * FROM [tblStock]", conn)
                cmd.CommandType = CommandType.Text
                Dim drStudents As SqlDataReader = cmd.ExecuteReader()
                GridView1.DataSource = drStudents

                'Colouring GridView Column
                'GridView1.Columns(5).ItemStyle.BackColor = System.Drawing.Color.Violet
            End Using
        End If
    End Sub

Now Coloring GridView Cell, Row & Column Based on Condition:
C# Code:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            //Colouring GridView CELL based on condition
            if (Convert.ToInt32(e.Row.Cells[3].Text) < 20000)
                e.Row.Cells[3].BackColor = System.Drawing.Color.Red;
            //Colouring GridView Row based on condition
            if (Convert.ToInt32(e.Row.Cells[3].Text) > 40000)
                e.Row.BackColor = System.Drawing.Color.Green;
                e.Row.ForeColor = System.Drawing.Color.White;

            //Colouring GridView Column based on condition
            if (Convert.ToInt32(e.Row.Cells[5].Text) > 0)
                GridView1.Columns[5].ItemStyle.BackColor = System.Drawing.Color.Navy;

VB.Net Code:

    Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            'Colouring GridView CELL based on condition
            If Convert.ToInt32(e.Row.Cells(3).Text) < 20000 Then
                e.Row.Cells(3).BackColor = System.Drawing.Color.Red
            End If

            'Colouring GridView Row based on condition
            If Convert.ToInt32(e.Row.Cells(3).Text) > 40000 Then
                e.Row.BackColor = System.Drawing.Color.Green
                e.Row.ForeColor = System.Drawing.Color.White
            End If

            'Colouring GridView Column based on condition
            If Convert.ToInt32(e.Row.Cells(5).Text) > 0 Then
                GridView1.Columns(5).ItemStyle.BackColor = System.Drawing.Color.Navy
            End If
        End If
    End Sub

Hope now you can represent data with interactive look. Happy coding !!

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Database, Gridview, SQL Server, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *