4

我有一个加载DataGridView. 我创建了一个CellPainting事件来根据单元格值对行进行着色。我之所以这样做是CellPainting因为遍历 中的行Datagridview并绘制它们花费的时间太长,所以这更有效。

问题

  • CellPainting事件不适用于表单加载。这意味着所有行都被隐藏,直到我滚动或单击它们,然后它们会根据单元格值正确绘制。
  • 我注意到的另一件事是缺少列标题。另一个问题是当我DataGridView使用滚动条向下滚动 Rows 时,CellPainting再次调用了,我必须等待几秒钟,因为它会重新绘制行颜色。这很烦人,尤其是当我有数千行时,每次滚动都会导致延迟。

所有这些问题都消失了,DatagridView当我删除方法时,列标题和行都出现了CellPainting,所以问题显然存在。以下是我的片段,感谢您的帮助。

private void timeLineDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
        //only bold and/or color the rows that are false
                if ((Boolean)timeLineDataGridView.Rows[e.RowIndex].Cells[12].Value == false)
                {
                    //get timestamp and go ahead and bold it 
                    DateTime eventTime = DateTime.Parse(timeLineDataGridView.Rows[e.RowIndex].Cells["TIMESTAMP"].Value.ToString());
                    timeLineDataGridView.Rows[e.RowIndex].DefaultCellStyle.Font = this.boldFont;


                        if (eventTime < this.delay_warn_time3)
                        {
                            timeLineDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                        }
                        else if (eventTime < this.delay_warn_time2)
                        {
                            timeLineDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Orange;
                        }
                        else if (eventTime < this.delay_warn_time1)
                        {
                            timeLineDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
                        }
                }
        }
4

1 回答 1

1

请尝试使用DataGridView.CellFormatting事件。当单元格的内容需要格式化以显示时发生。

在这种情况下应该更合适。

编辑

似乎它解决了除了滚动问题之外的所有问题。

滚动时如何使 CellFormatting 事件不触发

您可以在您的DataGridView.CellFormatting方法中使用的类中添加一个标志(一个布尔变量)来测试网格是否正在滚动,然后DataGridView.Scroll添加事件来标记这个标志。

bool _IsScrolling = false;
void DataGridView1_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e)
{
    if (e.Type == ScrollEventType.EndScroll) 
        {
        _IsScrolling = false;
    } else 
        {
        _IsScrolling = true;
    }
}

这是一个理论上的答案。如果您尝试但不起作用(e.Type从不ScrollEventType.EndScroll),您将对以下内容感兴趣:

于 2013-08-16T20:20:04.123 回答