3
Answers

Change GridView row color based on condition

Garima Bansal

Garima Bansal

1y
497
1

 I want to change a particular row color of a gridview based on some condition.

Answers (3)
4
Vishal Joshi

Vishal Joshi

244 7.8k 135.4k 1y

Hello

You can use the Grid Row Data Bound event to set conditions based on row color. please check the below sample code.

cs File Code

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
	if (e.Row.RowType == DataControlRowType.DataRow)
    {
		if (Convert.DateTime(DataBinder.Eval(e.Row.DataItem, "Date")) == DateTime.Now.AddDays(-10))
		{
		  e.Row.BackColor = System.Drawing.Color.Cyan;
		}
	}
}

 

Aspx Page Code

<asp:GridView ID="grd_id" runat="server" CellPadding="6" AutoGenerateColumns="False" OnRowDataBound="grd_RowDataBound">

 

Thanks

Vishal Joshi

Accepted
4
Amit Mohanty

Amit Mohanty

16 52.2k 6.1m 1y

You can change the color of a particular row in a GridView based on some condition by using the RowDataBound event.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string value = DataBinder.Eval(e.Row.DataItem, "ColumnName").ToString();
        
        if (value == "SomeCondition")
        {
            e.Row.BackColor = System.Drawing.Color.Yellow;
        }
    }
}
3
Abhishek  Yadav

Abhishek Yadav

107 17.2k 348.1k 1y
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // You can change this condition as per your requirement
        string value = DataBinder.Eval(e.Row.DataItem, "ColumnName").ToString();

        if (value == "SomeCondition")
        {
            e.Row.BackColor = System.Drawing.Color.Yellow; // Change color to yellow
            // You can change the color to any other color as per your requirement
        }
    }
}

try this