我有一个加载 DataGridView
的表单。我创建了一个 CellPainting
事件来根据单元格值为行着色。我做了一个 CellPainting
,因为遍历 Datagridview
中的行并绘制它们花费的时间太长,因此效率更高。
问题
CellPainting
事件不用于表单加载。这意味着所有行都是隐藏的,直到我滚动或单击它们,然后它们才会根据单元格值正确绘制。- 我注意到的另一件事是缺少列标题。另一个问题是,当我使用滚动条向下滚动
DataGridView
行时,再次调用CellPainting
,我必须等待几秒钟,因为它会重新绘制行颜色。这很烦人,尤其是当我有数千行时,每次滚动都会导致延迟。
所有这些问题都消失了,当我删除 CellPainting
方法时,DatagridView
列标题和行都出现了,所以问题显然存在。以下是我的代码片段,感谢您的帮助。
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;
}
}
}
最佳答案
试试 DataGridView.CellFormatting事件代替。 当单元格的内容需要格式化以显示时发生。
在这种情况下应该更合适。
编辑
它似乎解决了除滚动问题之外的所有问题。
how do I get the CellFormatting Event to not fire when I scroll
您可以在您的类中添加一个标志(一个 bool 变量),您在 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
),您将对以下内容感兴趣:
关于c# - DatagridView 单元格绘画无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281464/