Reputation: 53
I need to change the colour of gridview cells based on the data value. I can quite easily do this using a datarow view in the Gridviews RowDataBound Event and an if statement (see below), however I need to do this on 30 columns which will be rather long winded and a pain to change if the business rules change. How can I encapsulate the following into a reusable method that I can call and just pass in the data column and the cell index ?
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
int A = Int32.Parse(drv["A"].ToString());
if (A <= 74)
{
e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
}
}
}
Upvotes: 1
Views: 925
Reputation: 53
Figured it out - Mr Meckley put me on the right track and my working (if inelegant) solution is:
public void SetColor2(GridViewRow row, string columnName, int cellIndex)
{
if (row.RowType == DataControlRowType.DataRow)
{
int number = Convert.ToInt32(columnName);
if (number == 0)
{
row.Cells[cellIndex].Text = "";
return;
}
else if ((number > 0) && (number <= 74))
{
row.Cells[cellIndex].BackColor = System.Drawing.Color.Red;
row.Cells[cellIndex].ForeColor = System.Drawing.Color.Black;
return;
}
}
}
Usage:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
SetColor2(e.Row, drv["A"].ToString(), 2);
SetColor2(e.Row, drv["B"].ToString(), 3);
etc...
}
}
Upvotes: 1
Reputation: 7591
public void SetColor(DataGridViewRow row, string columnName, int cellIndex)
{
var data = (GridViewRow)row.DataItem;
int number = Convert.ToInt32(data[columnName]);
if (number > 74) return;
row.Cells[cellIndex].BackColor = Color.Red;
}
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataRowType.DataRow) return;
SetColor(e, "A", 2);
}
Upvotes: 2