【问题标题】:DataGridView Row Color Doesn't ChangeDataGridView 行颜色不变
【发布时间】:2016-12-02 09:29:13
【问题描述】:

您好,我正在使用 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事件
  • 它不起作用:(

标签: c# datagridview


【解决方案1】:

你应该在dataGridView1_CellFormatting事件中调用这个HighlateIfEmpty(), 供您参考,我添加了link,请仔细阅读。

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx

【讨论】:

  • 但是这里会为每个单元格一遍又一遍地调用它!
  • 是的,在cell formatting 事件中它会调用每个单元格,因此请避免使用 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; } }
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多