[英]Color Cell in one GridView based on cell value in another GridView
I am trying to color a cell in GridView1 based on a value of a cell of a GridView2.我正在尝试根据 GridView2 的单元格的值为 GridView1 中的单元格着色。 Say, " If the GridView1 Column[3] Cell value = ' ' then a GridView2 Column[0] Row.Cells.BackColor = Color.Orange; ".说,“如果 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.以下代码为整个 GridView1 而不是特定单元格着色。
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.如果存在与 GridView2 中当前绑定的单元格值匹配的值,它将在 GridView1 的每个单元格中查找。 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
orTemplateField
, auto-generated columns cannot be searched.这仅在 GridView1 中的列是BoundField
或TemplateField
时才有效,无法搜索自动生成的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.