Thursday 22 August 2013

Alternate Color Rows in Gridview based on some condition

To show the alternate color to the rows, there is an attribute alternate template in gridview which gives the alternate color, but if the alternate color depends on the data value in the gridview then we need to write the logic accordingly. I have a gridview which is having month wise-weekly data. now weeks in a month varies, I needed to show the color change of alternate month.

the gridview is bind as usual, with data from the database table which is being fetched using ADO.net into the dataset and then bind with the gridview.

next comes the logic to change the alternate color:

private void BindGrid()
{

SqlConnection con = new SqlConnection("Data Source=datasource ;user id=sa;password=password;Initial Catalog=databasename");
con.Open();

SqlDataAdapter sda = new SqlDataAdapter("select * from TableName con);sda.Fill(ds);
ViewState[
"Dataset"] = ds;gvClarityCalendar.DataSource = ds.Tables[0];
gvClarityCalendar.DataBind();
//change the color of the rows
SetRowBackColor(gvClarityCalendar);
con.Close();
}


public void SetRowBackColor(GridView gv)
{
  string strPreviousDataKeyValue = "";
System.Drawing.
Color RowColor = System.Drawing.Color.PaleGoldenrod;
foreach (GridViewRow row in gv.Rows){

if (!strPreviousDataKeyValue.Equals(gv.Rows[row.RowIndex].Cells[0].Text.ToString()))RowColor = RowColor == System.Drawing.
Color.AliceBlue ? System.Drawing.Color.PaleGoldenrod : System.Drawing.Color.AliceBlue;gv.Rows[row.RowIndex].BackColor= RowColor;
strPreviousDataKeyValue = gv.Rows[row.RowIndex].Cells[0].Text.ToString();
}





In the above figure, we can see the color is alternate according to the data,here it is accirding to the name of the month.

2 comments:

  1. Replies
    1. its not just enabling alternate color,but based on certain condition, i.e. for a group of similar values will have same color alternatively the other group will have different color.

      Delete