2009-12-19 40 views
0

我在winForm中合併datagridview標題時出現問題。winform - 合併datagridview標題

我使用此代碼:

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); 
     } 
    } 

滾動前柵格。一切都很好,但滾動後標題文本更改爲垃圾文本。 請檢查snapshot

我將不勝感激有人可以幫助我找到一個好的解決方案。

ali.mz

回答

1

我認爲最簡單的方法是在每次datagridview的滾動時間無效合併頭部的細胞。您將需要一個處理程序添加到滾動事件:

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

下面是滾動事件處理程序實現:

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); 
} 

希望這會有所幫助,至於