views:

553

answers:

1

I have a custom ComboBox control that I want to use in a DataGridView. I first inherited DataGridViewCell and am trying to achieve my goals overriding the Paint() method. The problem is that after inheriting DataGridViewColum and setting the CellTemplate property to a new instance of my CustomDataGridViewCell class, the cell is grey with no contents.

I'm not really sure that this is the correct approach, so any direction is appreciated.

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

Oh, and the _cBox class variable references an object instantiated at variable declaration.

+1  A: 

It was a fairly simple fix, pity no one answered. It would have saved me quite a bit of time.

I had to correct the coordinates to be relative to the window instead of the DataGridView, call Controls.Add for the owning form, and reposition the control in front of the DataGridView:

protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, 
DataGridViewPaintParts paintParts)
{
    // Just paint the border (because it shows outside the ComboBox bounds)
    this.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
    
    // Create ComboBox and set properties
    _cBox = new CheckedComboBox();
    _cBox.DropDownHeight = 1;
    _cBox.IntegralHeight = false;
    _cBox.Location = new Point(this.DataGridView.Location.X + cellBounds.X, this.DataGridView.Location.Y + cellBounds.Y);
    _cBox.Size = new Size(cellBounds.Width, cellBounds.Height);
    _cBox.ValueSeparator = ", ";
    
    // Add to form and position in front of DataGridView
    this.DataGridView.FindForm.Controls.Add(_cBox);
    _cBox.BringToFront();
}
Rob