首先我要说的是,我找到了以下内容,但没有一个解决方案对我有用。
Cells gets overlapped and painted when Scroll happens in DataGridView
DataGridView overrides my custom row painting
DataGridView CellPainting Not Fully Working on Scroll
在CellPainting和RowPostPaint中,我使用e.Graphics.DrawLine
,当网格加载时,所有内容都按照我的预期绘制。我有两个问题:
以下是我的两个油漆事件:
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
int width = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
width += col.Width;
if (col.Index % 3 == 0)
e.Graphics.DrawLine(Pens.Black, width + 1, e.RowBounds.Top, width + 1, e.RowBounds.Bottom - 1);
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
int width = 0;
if (e.RowIndex == -1)
{
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
width += col.Width;
if (col.Index % 3 == 0)
e.Graphics.DrawLine(Pens.Black, width + 1, e.CellBounds.Top +1, width + 1, e.CellBounds.Bottom - 2);
else
e.Graphics.DrawLine(Pens.White, width + 1, e.CellBounds.Top +1, width + 1, e.CellBounds.Bottom - 2);
}
}
}
更新代码
我将我的油漆事件合并到CellPainting
事件中,并根据TaW的建议进行了一些更改。仍然没有工作,但我觉得我现在只是缺少一些小东西。
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1)
{
if (e.ColumnIndex % 3 == 0)
e.Graphics.DrawLine(Pens.Black, e.CellBounds.Right, e.CellBounds.Top + 1, e.CellBounds.Right, e.CellBounds.Bottom - 2);
else
e.Graphics.DrawLine(Pens.White, e.CellBounds.Right, e.CellBounds.Top + 1, e.CellBounds.Right, e.CellBounds.Bottom - 2);
}
else
if (e.ColumnIndex % 3 == 0)
e.Graphics.DrawLine(Pens.Black, e.CellBounds.Right, e.CellBounds.Top + 1, e.CellBounds.Right, e.CellBounds.Bottom - 2);
}
答案 0 :(得分:1)
您错过了正确CellPainting
的几个步骤:
你需要
以下是一个例子:
private void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
Rectangle cr = e.CellBounds;
e.PaintBackground(cr, true); // (2)
e.PaintContent(cr); // (3)
if (e.ColumnIndex % 2 == 0)
{
e.Graphics.DrawLine(Pens.LawnGreen, cr.Right-2, cr.Top + 1,
cr.Right-12, cr.Bottom - 2);
}
e.Handled = true; // (1)
}
您可以更改事物的顺序,只需确保首先绘制背景!
请注意,与评论相反,无需使用Scroll
对Invalidate
事件进行编码。