Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to change the gridview cell color to red if the value is <=0. I have tried the below piece of code and it doesn't take the cell value of each row.

How can I get each cell value of gridview.

What I have tried:

I am using the below piece of code in RowDataBound event.

if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                for (int i = 0; i < GridView1.Columns.Count; i++)
                {
                    TableCell cell = row.Cells[i];
                    int quantity = int.Parse(cell.Text);
                    if (quantity <= 0)
                    {
                        cell.ForeColor = Color.Red;
                    }
                }
            }
        }
Posted
Updated 11-Jan-18 1:58am
Comments
Karthik_Mahalingam 11-Jan-18 8:52am    
can you post the mark up code for gridivew.

1 solution

You're pretty close... If you would like to change forecolor for specific column, for example: "Rate", check this:

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // grab the Label Control.
        Label lblRate = e.Row.FindControl("lblRate") as Label;
        // get the value from the datasoure like this
        Double rate = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Rate")));
        if (rate <= .0)
        {
            // grab the cell where that label resides
            DataControlFieldCell d = lblRate.Parent as DataControlFieldCell;
            // change the backcolor like this
            d.BackColor = System.Drawing.Color.Red;
            // change the row color like this
            e.Row.BackColor = System.Drawing.Color.LightBlue;
            // change the text color like this
            lblRate.ForeColor = System.Drawing.Color.White;
        }
    }
}



For further details, please see: How to make a Gridview Row Color/ Cell Color/ Text Color « Devils Work[^]

You might be interested in some sort of validation too: Tutorial 19: Adding Validation Controls to the Editing and Inserting Interfaces[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900