views:

335

answers:

1

Dear friends

I have a problem with merge the datagridview headers in winForm.

I using this code :

void dataGridView1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle r1 = dataGridView1.GetCellDisplayRectangle(2, -1, true);
        Rectangle r2 = dataGridView1.GetCellDisplayRectangle(3, -1, true);

        r1.X += 1;
        r1.Y += 2;
        r1.Width += r2.Width - 2;
        r1.Height -= 6;

        using (SolidBrush br = new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.BackColor))
        {
            e.Graphics.FillRectangle(br, r1);
        }

        //draw text
        using (SolidBrush br = new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor))
        {
            StringFormat sf = new StringFormat
                                  {
                                      LineAlignment = StringAlignment.Center,
                                      Alignment = StringAlignment.Center
                                  };
            e.Graphics.DrawString("merged header", dataGridView1.ColumnHeadersDefaultCellStyle.Font, br, r1, sf);
        }
    }

before scrolling the grid . everything is fine but after scrolling the header text changed to garbage text. please check the snapshot .

I would appreciate it someone could help me to find a good solution.

ali.mz

A: 

I believe the easiest way would be to invalidate merged header's cells every time the datagridview is scrolled. You would need to add a handler to the Scroll event:

dataGridView1.Scroll += new System.Windows.Forms.ScrollEventHandler(this.dataGridView1_Scroll);

Below is scroll event handler implementation:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
    Rectangle rect = Rectangle.Union(
        dataGridView1.GetCellDisplayRectangle(2, -1, true), 
        dataGridView1.GetCellDisplayRectangle(3, -1, true));
    dataGridView1.Invalidate(rect);
}

hope this helps, regards

serge_gubenko