我使用包含纯文本的 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/