C# 更改DataGridView中某些单元格的样式

C# 更改DataGridView中某些单元格的样式,c#,.net,winforms,visual-studio-2010,datagridview,C#,.net,Winforms,Visual Studio 2010,Datagridview,我试图根据值是否与其他单元格中的值相同来更改DataGridView中某些单元格的颜色。遗憾的是,它不起作用。这是我认为应该有效的代码: for (int i = 0; i < dataGridView2.Rows.Count; i++) { for (int j = 1; j < 8; j++) for (int k = 8; k < 20; k++) if (dataGridView2.Rows[i].Cells[j].Val

我试图根据值是否与其他单元格中的值相同来更改DataGridView中某些单元格的颜色。遗憾的是,它不起作用。这是我认为应该有效的代码:

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
    for (int j = 1; j < 8; j++)
        for (int k = 8; k < 20; k++)
            if (dataGridView2.Rows[i].Cells[j].Value == dataGridView2.Rows[i].Cells[k].Value)
                dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Green;
}
dataGridView2.Refresh();
for(int i=0;i
所有列都是用typeof(int)创建的,所以它不应该是类型问题。调试还显示我的程序确实输入了if子句,但仍然没有显示更改


提前感谢您的帮助。

我正在使用的一个应用程序中执行此操作。正如我所能想到的,最好的方法是重写DataGridView.CellFormatting事件

在我的应用程序中,数据源的每一行上都有四个布尔属性,我想为每个属性添加一个彩色框

    void uxGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        try
        {
             var item = uxGrid.Rows[e.RowIndex].DataBoundItem as NiftyThing;
             if(item != null)
             {
                 if(item.Property1)
                 {
                     e.CellStyle.SelectedBackColor = e.CellStyle.BackColor = Color.Red;
                     //Don't display 'True' or 'False'
                     e.Value = string.Empty;
                 }
                 else if(item.Property2)
                 ...
             }      
        }
        catch { }
    }

我希望这有帮助

我正在我的一个应用程序中执行此操作。正如我所能想到的,最好的方法是重写DataGridView.CellFormatting事件

在我的应用程序中,数据源的每一行上都有四个布尔属性,我想为每个属性添加一个彩色框

    void uxGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        try
        {
             var item = uxGrid.Rows[e.RowIndex].DataBoundItem as NiftyThing;
             if(item != null)
             {
                 if(item.Property1)
                 {
                     e.CellStyle.SelectedBackColor = e.CellStyle.BackColor = Color.Red;
                     //Don't display 'True' or 'False'
                     e.Value = string.Empty;
                 }
                 else if(item.Property2)
                 ...
             }      
        }
        catch { }
    }

我希望这有帮助

你确定你的程序加入了if条款吗?我尝试在datagridview中的特定单元格上设置背景色,效果很好。您在哪里编写此代码?您确定您的程序输入了if子句吗?我尝试在datagridview中的特定单元格上设置背景色,效果很好。您在哪里编写此代码?