C#WinForms DataGridView背景颜色渲染太慢

我正在DataGridView中绘制我的行,如下所示:

private void AdjustColors() { foreach (DataGridViewRow row in aufgabenDataGridView.Rows) { AufgabeStatus status = (AufgabeStatus)Enum.Parse(typeof(AufgabeStatus), (string)row.Cells["StatusColumn"].Value); switch (status) { case (AufgabeStatus.NotStarted): row.DefaultCellStyle.BackColor = Color.LightCyan; break; case (AufgabeStatus.InProgress): row.DefaultCellStyle.BackColor = Color.LemonChiffon; break; case (AufgabeStatus.Completed): row.DefaultCellStyle.BackColor = Color.PaleGreen; break; case (AufgabeStatus.Deferred): row.DefaultCellStyle.BackColor = Color.LightPink; break; default: row.DefaultCellStyle.BackColor = Color.White; break; } } } 

然后我在OnLoad方法中调用它:

 protected override void OnLoad(EventArgs e) { base.OnLoad(e); AdjustColors(); } 

我更喜欢OnLoad到OnPaint或者其他东西..因为OnPaint经常被调用。

问题:为什么改变每一行的背景需要大约100-200毫秒? 早,我是doint CellPaint ..但滚动时刷新我有问题..

您应该让它通过覆盖CellFormatting事件来管理渲染,而不是一次更改整个DataGrid的颜色。 只有当它们实际显示在屏幕上时才会绘制行。

 private void aufgabenDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridViewRow row = aufgabenDataGridView.Rows[e.RowIndex]; AufgabeStatus status = (AufgabeStatus) Enum.Parse(typeof(AufgabeStatus), (string) row.Cells["StatusColumn"].Value); switch (status) { case (AufgabeStatus.NotStarted): e.CellStyle.BackColor = Color.LightCyan; break; case (AufgabeStatus.InProgress): e.CellStyle.BackColor = Color.LemonChiffon; break; case (AufgabeStatus.Completed): e.CellStyle.BackColor = Color.PaleGreen; break; case (AufgabeStatus.Deferred): e.CellStyle.BackColor = Color.LightPink; break; default: e.CellStyle.BackColor = Color.White; break; } } 

如果这仍然太慢,请尝试获取行绑定的真实对象:

 ... DataGridViewRow row = aufgabenDataGridView.Rows[e.RowIndex]; var aufgabe = (Aufgabe) row.DataBoundItem; AufgabeStatus status = aufgabe.Status; ... 

它可能是Enum.Parse调用,它的性能很差。 您应该尝试将其更改为字典查找,以查看是否可以提高性能。 看这篇文章

正如SwDevMan1所说,你应该首先去除Enum.Parse调用。 您是否使用数据绑定来填充网格? 如果是这样,您可以使用Rows [index] .DataBoundItem访问行的数据绑定对象并直接访问AufgabeStatus状态。

我建议的第二个调整是分别在操作网格之前和之后调用SuspendLayout()和ResumeLayout()。

如果属性与预期值不同,则仅设置属性也是一个好主意。 这样您就不会触发不必要的内部DataGridView开销。

如果一行中的所有单元格都以相同的方式格式化,则可以在行级别而不是单元格级别进行格式化。

 DataGridViewCellStyle rowStyle = row.DefaultCellStyle; if (rowStyle.BackColor != status.BackColor) { rowStyle.BackColor = status.BackColor; } 

不要尝试行格式为row.defaultcellstyle

在ufgabenDataGridView_CellFormatting中尝试单个单元格格式

细胞[0] = .style.backcolor color.yellow