C# WinForms DataGridView background color rendering too slow

后端 未结 5 1817
挽巷
挽巷 2021-02-20 14:52

I\'m painting my rows in a DataGridView like this:

private void AdjustColors()
    {            
        foreach (DataGridViewRow row in aufgabenDataGridView.Row         


        
5条回答
  •  被撕碎了的回忆
    2021-02-20 15:33

    Instead of changing the color of the whole DataGrid at once, you should let it manage the rendering by overriding the CellFormatting event. The rows will only be painted when they are actually displayed on the screen.

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

    If this is still too slow, try getting the real object the row is bound to:

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

提交回复
热议问题