日期:2014-05-17  浏览次数:21026 次

DataGridView 表头合并问题
通过重写DataGridView的OnCellPainting 重写绘制表头 但是拖动滚动条的时候 列上面的文字就乱掉了 

可能是因为性能问题 因为在不听的调用这个重写方法

我该怎么搞 高手给个解决方案

代码如下:
 public partial class RowMergeView : DataGridView
  {
  #region 构造函数
  public RowMergeView()
  {
  InitializeComponent();
  }
  #endregion
  #region 重写的事件
  protected override void OnPaint(PaintEventArgs pe)
  {
  // TODO: 在此处添加自定义绘制代码

  // 调用基类 OnPaint
  base.OnPaint(pe);
  }
  protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
  {
  try
  {
  if (e.RowIndex > -1 && e.ColumnIndex > -1)
  {
  DrawCell(e);
  }
  else
  {
  //二维表头
  if (e.RowIndex == -1)
  {
  if (SpanRows.ContainsKey(e.ColumnIndex)) //被合并的列
  {
  //画边框
  Graphics g = e.Graphics;
  e.Paint(e.CellBounds, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border);
   
  int left = e.CellBounds.Left, top = e.CellBounds.Top + 2,
  right = e.CellBounds.Right, bottom = e.CellBounds.Bottom;

  switch (SpanRows[e.ColumnIndex].Position)
  {
  case 1:
  left +=2;
  break;
  case 2:
  break;
  case 3:
  right -= 2;
  break;
  }

  //画上半部分底色
  g.FillRectangle(new SolidBrush(this._mergecolumnheaderbackcolor), left, top,right - left, (bottom - top) / 2);

  //画中线
  g.DrawLine(new Pen(this.GridColor), left, (top + bottom) / 2,right, (top + bottom) / 2);

  //写小标题
  StringFormat sf = new StringFormat();
  sf.Alignment = StringAlignment.Center;
  sf.LineAlignment = StringAlignment.Center;

  g.DrawString(e.Value + "", e.CellStyle.Font, Brushes.Black,
  new Rectangle(left, (top + bottom) / 2, right - left, (bottom - top) / 2), sf);
  left = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Left, true).Left - 2;

  if (left < 0) left = this.GetCellDisplayRectangle(-1, -1, true).Width;
  right = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Right, true).Right - 2;
  if (right < 0) right = this.Width;
   
  g.DrawString(SpanRows[e.ColumnIndex].Text, e.CellStyle.Font, Brushes.Black,