DataGridView行颜色不改变

3

你好,我正在开发Windows窗体应用程序,但遇到了一个问题。我们使用数据网格视图,如果某一行的一个或多个列为空,我希望将其突出显示。我不知道为什么,但我的代码无法实现。这是我的代码:

 public Form1()
    {
        InitializeComponent();
        var dtCombined = PopulateCombinedDatatable();       
        dataGridView.DataSource = dtCombined;
        HighlateIfEmpty();
    }

    public string[] FindFilePath()
    {
       //OPERATIONS
    }

    public DataTable PopulateCombinedDatatable()
    {

       //MY OPERATIONS
    }

    public void HighlateIfEmpty()
    {
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if ((string)cell.Value == string.Empty)
                {
                    cell.Style.BackColor = Color.BlueViolet;
                    cell.Style.SelectionBackColor = Color.Aquamarine;
                    row.DefaultCellStyle.SelectionBackColor = Color.BlueViolet;
                    row.DefaultCellStyle.ForeColor = Color.Yellow;
                    row.DefaultCellStyle.BackColor = Color.Aquamarine;
                }
            }
        }                      
    }

感谢您的提问... PS:此代码可以找到正确的列和行,但无法进行着色。

请稍后调用该函数,可以在FormLoad或FormShown事件中调用。 - TaW
它不起作用 :( - Berkin
2个回答

2

但是在这里,它将被反复调用以处理每个单元格! - TaW
单元格格式化 事件中,它会为每个单元格调用,因此避免使用 foreach,尝试这个方法,希望对您有所帮助。 private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 1) { if ((int)e.Value == 3) e.CellStyle.BackColor = Color.Blue; if ((int)e.Value == 2) e.CellStyle.BackColor = Color.Red; } } - Subash B

0

我知道这篇文章有点老了,但是无论如何……

在DataGridView上有一个DefaultCellStyle,里面有SelectionBackColorSelectionForeColor属性。

DataGridView使用样式继承的思想,以防您发现所选样式未被应用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接