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

PaN*_*1Me 9 c# datagridview winforms

我正在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;
            }
        }        
    }
Run Code Online (Sandbox Code Playgroud)

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

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

            AdjustColors();           
        } 
Run Code Online (Sandbox Code Playgroud)

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

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

Jul*_*lin 13

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

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;
  }

}
Run Code Online (Sandbox Code Playgroud)

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

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