Pages

Friday, November 11, 2011

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


    
//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;
             }
        }  
   }
 

No comments:

Post a Comment