Monday, May 31, 2010

Sometimes its is required to dynamically bind the background or fore ground color of grid view’s rows based on some conditions or database stored values when showing data to grid view.

Here I am giving a very easy and flexible solution for solving this problem……….
Step 1: Create a new website.
Step 2:Add a grid view to the aspx page as shown below

Step 3: on the code behind file’s page load event bind he grid view as follows..

DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Name");
DataColumn dc1 = new DataColumn("RColor");
DataRow dr = dt.NewRow();
dr[0] = "pal";
dr[1] = "Red";
DataRow dr1 = dt.NewRow();
dr1[0] = "gfhfgh";
dr1[1] = "Blue";
DataRow dr2 = dt.NewRow();
dr2[0] = "jhkk";
dr2[1] = "green";
GridView1.DataSource = dt;

Step 4: now on the row databound event of the gridview write the following code to set the rows color…….
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow) {
HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");
//for fore color set
//for background color
e.Row.Style.Add("background-color", hf.Value);
//you can also use the following code if you know the color in advance
//e.Row.BackColor = Color.FromName("#FAF7DA");
// e.Row.BackColor = Color.White;
Step 5:Now build the website and run. That’s all what you have o do.