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

在滚动网格之前。 一切都很好,但滚动后标题文本更改为垃圾文本。 请检查快照 。

我很感激有人可以帮我找到一个好的解决方案。

ali.mz

我相信最简单的方法是每次滚动datagridview时使合并的标题的单元格无效。 您需要为Scroll事件添加处理程序:

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

希望这会有所帮助,问候