2014-09-22 68 views
2

我有一個DataGridView我想設置一個標題行和列,如下圖所示: enter image description here如何設置標題爲DataGridView的行/列

文本1描述了列標題的含義和Text2的行。

我的問題是如果這是可能的,如果是這樣,如何做到這一點(覆蓋DataGridView繪製事件?)或你可以提供什麼其他的替代方案來實現這個目標?我希望它是優雅和直觀的。

編輯:

我結束了使用下面的代碼:

private void dataGridView_tagretTable_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
    { 
     if (e.ColumnIndex == -1 && e.RowIndex == -1) 
     { 
      // Clear current drawing, to repaint when user change header width 
      e.Graphics.Clear(System.Drawing.Color.White); 

      string drawString = "Text1"; 

      System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 8); 
      System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); 
      System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(); 

      // Measure string 
      SizeF stringSize = new SizeF(); 
      stringSize = e.Graphics.MeasureString(drawString, drawFont); 

      // offset from rectangle borders 
      float offset = 3; 

      // Set string start point 
      float x = offset; 
      float y = e.Graphics.ClipBounds.Height - stringSize.Height - offset; 
      e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat); 

      drawString = "Text2"; 

      // Measure string 
      stringSize = e.Graphics.MeasureString(drawString, drawFont); 

      // Set string start point 
      x = e.Graphics.ClipBounds.Width - stringSize.Width - offset; 
      y = offset; 
      e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat); 

      // Draw crossing line 
      Pen myPen = new Pen(Color.Black); 
      myPen.Width = 1; 
      e.Graphics.DrawLine(myPen, new Point(0, 0), new Point(e.ClipBounds.Width, e.ClipBounds.Height)); 

      drawFont.Dispose(); 
      drawBrush.Dispose(); 
      drawFormat.Dispose(); 
      myPen.Dispose(); 

      // Set min row header width 
      if (dataGridView_tagretTable.RowHeadersWidth < 150) 
      { 
       dataGridView_tagretTable.RowHeadersWidth = 150; 
      } 

      e.Handled = true; 
     } 
    } 

回答

4

很容易(幸運)。訂閱CellPainting事件,並查找行-1和列-1,然後畫:

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.ColumnIndex == -1 && e.RowIndex == -1) 
    { 
     e.Graphics.FillRectangle(Brushes.Red, e.ClipBounds); 
     e.Handled = true; 
    } 
} 

顯然,你需要畫的相關細節,我只是在做一個紅色矩形。確保您將事件標記爲Handled = true,否則控件將再次接管繪畫。

有關詳細信息,請參閱this MSDN Forums link

如果你想做一些類似於使文本可編輯的東西,你會希望完全從控件派生出來,而不是使用事件,覆蓋支持方法OnCellPainting並在那裏執行。這也將允許您公開ColumnHeadersTitleRowHeadersTitle的新屬性。

+1

謝謝!我設法實現了這一點。我正在用完整的代碼編輯我的問題。 – etaiso 2014-09-22 13:25:00

相關問題