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");
dt.Columns.Add(dc);
DataColumn dc1 = new DataColumn("RColor");
dt.Columns.Add(dc1);
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";
dt.Rows.Add(dr);
dt.Rows.Add(dr1);
dt.Rows.Add(dr2);
GridView1.DataSource = dt;
GridView1.DataBind();
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
e.Row.Style.Add("color","White");
//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.
Monday, May 31, 2010
Subscribe to:
Posts (Atom)