2009-08-19 24 views
1

我有一個自定義的ComboBox控件,我想在DataGridViewCell中使用。我首先繼承了DataGridViewCell,並試圖覆蓋Paint()方法在單元格中繪製ComboBox如何在DataGridViewCell中繪製自定義組合框?

我的問題是,在繼承DataGridViewColumn並將CellTemplate屬性設置爲我的CustomDataGridViewCell類的新實例後,該單元格變爲灰色且沒有內容。

cBox類變量在對象ctor中實例化。

protected override void Paint(Graphics graphics, Rectangle clipBounds, 
    Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, 
    object value, object formattedValue, string errorText, 
    DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle borderStyle, 
    DataGridViewPaintParts paintParts) 
{ 
   // Call MyBase.Paint() without passing object for formattedValue param 
   base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, 
     "", errorText, cellStyle, borderStyle, paintParts); 
    
   // Set ComboBox properties 
   this.cBox.CheckOnClick = true; 
   this.cBox.DrawMode = System.Windows.Forms.DrawMode.Normal; 
   this.cBox.DropDownHeight = 1; 
   this.cBox.IntegralHeight = false; 
   this.cBox.Location = new System.Drawing.Point(cellBounds.X, cellBounds.Y); 
   this.cBox.Size = new System.Drawing.Size(cellBounds.Width, cellBounds.Height); 
   this.cBox.ValueSeparator = ", "; 
   this.cBox.Visible = true; 
   this.cBox.Show(); 
} 

如何正確地在單元格中繪製ComboBox

回答

1

我做了相當簡單的修改,修復了我的問題。

我不得不糾正座標是相對於窗口而不是DataGridView,呼籲Controls.Add()的擁有形式,並在DataGridView前重新定位控制:

protected override void Paint(Graphics graphics, Rectangle clipBounds, 
    Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, 
    object value, object formattedValue, string errorText, 
    DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle borderStyle, 
    DataGridViewPaintParts paintParts) 
{ 
   // Just paint the border (because it shows outside the ComboBox bounds) 
  this.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, borderStyle); 

    int cellX = this.DataGridView.Location.X + cellBounds.X; 
    int cellY = this.DataGridView.Location.Y + cellBounds.Y; 

   // Create ComboBox and set properties 
   this.cBox = new CheckedComboBox(); 
   this.cBox.DropDownHeight = 1; 
   this.cBox.IntegralHeight = false; 
   this.cBox.Location = new Point(cellX, cellY); 
   this.cBox.Size = new Size(cellBounds.Width, cellBounds.Height); 
   this.cBox.ValueSeparator = ", "; 
    
   // Add to form and position in front of DataGridView 
   this.DataGridView.FindForm.Controls.Add(this.cBox); 
   this.cBox.BringToFront(); 
} 
+1

Hi.Could您提供文件在DataGridView中有一個CheckedCombBox? – San 2011-04-26 07:34:36