Home > ASP.Net > Change GridView Cell Color According to Condition

Change GridView Cell Color According to Condition


try this example to Change GridView Cell Color According to Condition

Step1 : Create Database which contains a table called “Projects” with the following schema

  • Id –> int (Primary Key)
  • Name –> nvarchar
  • Status –> nvarchar (Can be Open or Closed)

Step2 :- Create a new website and add new web page and drag SQLDataSource and Gridview Control

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="Id" DataSourceID="SqlDataSource1" ForeColor="#333333"
            <RowStyle BackColor="#EFF3FB" />
                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [Projects]"></asp:SqlDataSource>

and in code behind :

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            if (e.Row.Cells[2].Text == "Open")
                //e.Row.BackColor = System.Drawing.Color.Red;
                e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
            if (e.Row.Cells[2].Text == "Closed")
                //e.Row.BackColor = System.Drawing.Color.Green;
                e.Row.Cells[2].BackColor = System.Drawing.Color.Green;

Hope this helps

Good Luck

Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: