一个GridView中的Color Cell基于另一个GridView中的单元格值

时间:2017-02-02 17:34:48

标签: c# gridview formatting cell

我正在尝试根据GridView2的单元格值为GridView1中的单元格着色。说,“如果GridView1 Column [3] Cell value =''那么GridView2 Column [0] Row.Cells.BackColor = Color.Orange;”。

以下代码为整个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;

            }

        }
   }

1 个答案:

答案 0 :(得分:1)

这是一个可以帮助您入门的代码段。如果存在与GridView2中当前绑定的单元格值匹配的值,它将查看GridView1的每个单元格。当匹配时,它会将单元格着色为绿色。

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;
                    }
                }
            }
        }
    }
}
  

这仅在GridView1中的列为任何一个时才有效   BoundFieldTemplateField,自动生成的列不能   搜索。