Reputation: 321
I have a grid view that is populated dynamically through a stored procedure
I would like to ask how can I loop through each row and set the colour of the value for column17 upon populating the gridview? For example, for value range between 1 - 20 I would like to the colour to be green, value between 21-40 to be orange and 41 - 60 to be red?
My codes to populate the gridview:
using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@param1", SqlDbType.VarChar).Value = DATE;
cmd.Parameters.Add("@param2", SqlDbType.VarChar).Value = Key;
string query = cmd.CommandText;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Gridview1.DataSource = ds.Tables[0];
Gridview1.DataBind();
Upvotes: 0
Views: 651
Reputation: 105
I'd say to use
Row[xx].Cells[xx].BackColor = System.Drawing.Color.xxx
in the databound event of the row. You can look up for available colors on the net.
hope it helps
Upvotes: 0
Reputation: 21795
You can use the RowDataBound event of gridview:-
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[16].BackColor = System.Drawing.Color.Green;
}
}
This will set the background color of all the rows in column 17
(I have used 16
since it's zero index based) to green except header. If you want to set the color of header as well then don't check the DataRow
condition.
Also, if you want to color few range like from column 1-20 then you can use a for
loop.
Upvotes: 1