如何在DataGridViewCell中绘制自定义ComboBox?

时间:2009-08-19 14:48:06

标签: .net combobox paint datagridviewcolumn

我想在ComboBox中使用自定义DataGridViewCell控件。我首先继承了DataGridViewCell,并尝试覆盖Paint()方法以在单元格中绘制ComboBox

我的问题是,在继承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 个答案:

答案 0 :(得分:1)

我做了相当简单的修改,解决了我的问题。

我必须更正相对于窗口而不是DataGridView的坐标,为拥有表格调用Controls.Add(),并将控件重新定位在DataGridView:<前面/ p>

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