当在DataGridView中发生Scroll时,单元格会重叠并绘制

时间:2016-02-04 18:59:50

标签: c# winforms datagridview

最初我在用户滚动时在单元格中显示数据我需要在DataGridView中加载更多数据。

我使用DataGridView CellPainting绘制线条。 当我开始在datagridview中滚动时,单元格会重叠并完全改变输出。

public partial class Display : Form
{
    public Display()
    {
        InitializeComponent();
        LoadData();
    }

    // To create the rows and columns and fill some data
    private void LoadData()
    {
        int columnSize = 10;

        DataGridViewColumn[] columnName = new DataGridViewColumn[columnSize];

        for (int index = 0; index < columnSize; index++)
        {
            columnName[index] = new DataGridViewTextBoxColumn();

            if (index == 0)
            {
                columnName[index].Name = "Name";
                columnName[index].HeaderText = "Name";
            }
            else
            {
                columnName[index].Name = (index).ToString();
                columnName[index].HeaderText = (index).ToString();
            }
            columnName[index].FillWeight = 0.00001f;
            columnName[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

            dataGridView1.Columns.Add(columnName[index]);
        }

        for (int rowIndex = 0; rowIndex < columnSize; rowIndex++)
        {
            dataGridView1.Rows.Add((rowIndex + 1).ToString());
            dataGridView1.Rows[rowIndex].HeaderCell.Value = (rowIndex + 1).ToString();
        }
    }

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        Rectangle rectPos1 = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
        Pen graphPen = new Pen(Color.Red, 1);
        Graphics graphics = this.dataGridView1.CreateGraphics();
        Point[] points =
        {
                new Point(rectPos1.Left , rectPos1.Bottom), 
                new Point(rectPos1.Right, rectPos1.Bottom),
                new Point(rectPos1.Right, rectPos1.Top)
        };
        graphics.DrawLines(graphPen, points);
        e.PaintContent(rectPos1);
        e.Handled = true;
    }
}

Sample Download Link

我在下面的图片中显示了

enter image description here

我如何避免它,请帮我解决这个问题。

1 个答案:

答案 0 :(得分:4)

有几个问题。首先,您应该几乎总是使用从PaintEventArgs获得的提供的Graphics对象。 CreateGraphics是一个易于擦除的临时画布。您获得的参数之一是CellBounds矩形,因此您可以使用它。你的线实际上是在矩形之外绘制的,而你没有清除以前的内容,所以你的代码应该是这样的:

Rectangle rectPos1 = e.CellBounds;
e.Graphics.FillRectangle(Brushes.White, rectPos1);
Graphics graphics = e.Graphics; // this.dataGridView1.CreateGraphics();
Point[] points =
  {
    new Point(rectPos1.Left , rectPos1.Bottom - 1), 
    new Point(rectPos1.Right - 1, rectPos1.Bottom - 1),
    new Point(rectPos1.Right - 1, rectPos1.Top)
  };
graphics.DrawLines(Pens.Red, points);
e.PaintContent(rectPos1);
e.Handled = true;