Как нарисовать пользовательский ComboBox внутри DataGridViewCell? - PullRequest
1 голос
/ 19 августа 2009

У меня есть пользовательский 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 Ответ

1 голос
/ 20 августа 2009

Я сделал довольно простое изменение, которое исправляет мою проблему.

Мне пришлось исправить координаты относительно окна вместо 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();
}
...