Pregunta

Tengo una costumbre ComboBox control que quiero usar en un DataGridViewCell. Primero heredé DataGridViewCell y estoy tratando de anular el Paint() método para pintar el ComboBox en la celda.

Mi problema es que después de heredar DataGridViewColumn y establecer el CellTemplate propiedad a una nueva instancia de mi CustomDataGridViewCell clase, la celda es gris sin contenido.

los cBox La variable de clase se instancia en el objeto 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();
}

¿Cómo puedo pintar correctamente el ComboBox en la celda?

¿Fue útil?

Solución

Hice un cambio bastante simple que soluciona mi problema.

Tuve que corregir las coordenadas para ser relativas a la ventana en lugar de la DataGridView, llamar Controls.Add() para la forma de propiedad, y reposicione el control frente al 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();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top