I want to change my grid view row/cell background color depend on grid view cell or column value. I have a gridview asp.net (WebForms), one column which has quantity (int). depend on this value, every row background color should be change dynamically.
How to change gridview row color in c# / asp.net
1.4k Views Asked by arbabu AtThere are 2 best solutions below
On
Let's build a gridview but use a Bootstrap table class. The result will be a HTML bootstrap class table.
So, we have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" Width="50%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server"
Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And it looks like this:
Now, that is a rather ugly looking table.
So, let's add a Bootstrap "table" class, and like magic, we get a nice formatted table.
So, the gv markup is now this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" Width="50%"
CssClass="table table-hover"
The rest remains the same!
The result now is a nice Bootstrap formatted table.
We get this:
Note how very nice the resulting gridview table is - it's now a Bootstrap formatted table, and one that as above shows, even re-sizes very nicely.
So now that we have that formatted Bootstrap table, the next goal is to change the color of each row.
Let's format each row as skyblue for when the column is Active.
As suggested, the common approach is to use the row data bound event.
So, we now have this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
if ((bool)gData["Active"])
e.Row.BackColor = System.Drawing.Color.LightSteelBlue;
}
}
And the result is this:
And I suppose for fun, you can assign the row a CSS attribute, or even a class.
So then this:
if ((bool)gData["Active"])
e.Row.Style.Add("background-color", "LightSteelBlue");
The result will be the same effect as the first example code.


