Working with GridView - Changing cell/row/text color based on condition



If the price of the product is less than 90 then change the cell color in GridView

    
//Fires after every row data bound
  protected void gvCities_RowDataBound(object sender, GridViewRowEventArgs e)
    { 
        // Checking if row type 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // find the label control
            Label lblPrice = e.Row.FindControl(“lblPrice”) as Label;

            // read the value from the datasoure 
            Double Price = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, “Rate”)));

            if (Price < 90.00)
            {
                // get the cell where that label contains
                DataControlFieldCell d = lblPrice.Parent as DataControlFieldCell; 

                // to change the backcolor 
                d.BackColor = System.Drawing.Color.Blue;

                // to change the row color by setting
                e.Row.BackColor = System.Drawing.Color.Red; 

                // to change the text color like this
                lblPrice.ForeColor = System.Drawing.Color.Green;
             }
        }  
   }
 

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.