I am trying to color a cell in GridView1 based on a value of a cell of a GridView2. Say, " If the GridView1 Column[3] Cell value = ' ' then a GridView2 Column[0] Row.Cells.BackColor = Color.Orange; ".
The following code colors the entire GridView1 and not a particular cell.
protected void GridView2_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Enabled"));
if (status == "False")
{
GridView1.RowStyle.BackColor = Color.Red;
}
}
}
Here is a snippet to get you started. It will look in every cell of GridView1 if there is a value that matches with the cell value currently being bound in GridView2. When there is a match it will color the cell green.
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//loop all columns in the row
for (int i = 0; i < row.DataView.Count; i++)
{
string cellValue = row[i].ToString();
//loop all rows in gridview1
for (int j = 0; j < GridView1.Rows.Count; j++)
{
//loop all cells in gridview1
for (int k = 0; k < GridView1.Columns.Count; k++)
{
string cellValueCompare = GridView1.Rows[j].Cells[k].Text;
//compare values and color cell
if (cellValue == cellValueCompare)
{
GridView1.Rows[j].Cells[k].BackColor = Color.Green;
}
}
}
}
}
}
This will only work if the columns in GridView1 are either
BoundField
or TemplateField
, auto-generated columns cannot be
searched.