Skip to main content
 首页 » 编程设计

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

2024年02月05日12exmyth

最初我在用户滚动时在单元格中显示数据,我需要在 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

我已经在下图中显示了

我怎样才能避免它,请帮我解决这个问题。

请您参考如下方法:

几个问题。首先也是最重要的,您应该几乎总是使用从 PaintEventArgs 获得的提供的 Graphics 对象。 CreateGraphics 是一个可以轻松删除的临时 Canvas 。您获得的参数之一是 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;