在列标题上绘制矩形

时间:2013-07-16 12:14:56

标签: c# winforms graphics

我在datagridview中的列标题上绘制矩形,但在向右滚动时,它会消失,就像在图片中一样(scroll.png)enter image description here enter image description here

这是我的代码

Rectangle r1;
void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    string[] monthes = { "APPLE", "MANGO", "CHERRY", "GRAPES", "PINEAPPLE" };
    for (int j = 0; j < this.dataGridView1.ColumnCount; )
    {
        r1 = this.dataGridView1.GetCellDisplayRectangle(j, -1, true);
        int w2 = this.dataGridView1.GetCellDisplayRectangle(j + 1, -1, true).Width;
        r1.X += -2;
        r1.Y += 30;
        r1.Width = r1.Width + w2 - 1;
        r1.Height = r1.Height / 3 - 2;
        e.Graphics.FillRectangle(new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.BackColor), r1);
        StringFormat format = new StringFormat();
        format.Alignment = StringAlignment.Center;
        format.LineAlignment = StringAlignment.Center;
        e.Graphics.DrawRectangle(new Pen(Color.Black), r1);
        e.Graphics.DrawString(monthes[j / 2], this.dataGridView1.ColumnHeadersDefaultCellStyle.Font, new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor), r1, format);

        j += 2;
    }
}

void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
    Rectangle rtHeader = this.dataGridView1.DisplayRectangle;
    rtHeader.Y += 0;
    rtHeader.Height = this.dataGridView1.ColumnHeadersHeight;
    this.dataGridView1.Invalidate(rtHeader);
}

1 个答案:

答案 0 :(得分:0)

我测试了您的代码,负责您所描述的行为的行是this.dataGridView1.Invalidate(rtHeader);

因此,您有两个解决方案:

  • 删除上述行。
  • 或者将矩形放在单元格中(在第一行中,没问题),而不是在标题中。