c# - visual studio c# DataGridView 在排序后保持背景颜色

标签 c# winforms datagridview datatable

我使用包含纯文本的 DataTable 填充了 DataGridView。后来,我使用以下方法设置特定单元格的背景颜色:

grid.Rows[row].Cells[col].Style.BackColor = setColor;

在我单击 DataGridView 中的列排序按钮之前,一切正常。我想知道是否有办法在排序后保持背景颜色,而不管单元格的文本值如何。一旦我设置了该单元格的背景颜色,它就会在排序后记住该背景颜色。

我见过其他使用

的例子
CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)

事件处理程序,但他们在这里编写的代码似乎总是有先入为主的概念,即单元格的背景需要与单元格的文本内容相关的颜色(例如:如果 cellText == "Critical"...)。这对我来说不起作用,我只需要它记住哪些单元格设置为特定颜色。

有什么帮助吗?

最佳答案

使用“DataBindingComplete”事件!

例如

    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
            if (Convert.ToDateTime(row.Cells["Effective Date"].Value) > DateTime.Now)
            {
                row.DefaultCellStyle.BackColor = Color.LightYellow;
            }
            else { row.DefaultCellStyle.BackColor = Color.LightGreen; }
    }

关于c# - visual studio c# DataGridView 在排序后保持背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26782368/

相关文章:

c# - Windows Phone 8.1 WinRT 内存泄漏与 ObservableCollection

c# - 如何在 .NET 中实现极致品牌化/国际化

c# - 将类库公开为 "WCF Data Service"

c# - 调用 Assert.IsInstanceOfType 时如何排除祖先?

.net - Winforms MenuStrip带下划线的热键字母

c# - DataGridView 自动调整高度

c# - 在 gridview 和数据上添加一个额外的列

.net - DataGridView - "Cell Selection Style"- 编辑单元格

windows - 寻找 Forms.Screen.DeviceName 的可靠映射以监控 EDID 信息

c# - 有没有办法在 C# 中实现平面文本框?