Come posso disegnare un ComboBox personalizzato all'interno di un DataGridViewCell?
-
18-09-2019 - |
Domanda
Ho un controllo ComboBox
personalizzato che voglio usare in un DataGridViewCell
. Ho ereditato DataGridViewCell
e sto cercando di eseguire l'override del metodo Paint()
di dipingere il ComboBox
nella cella.
Il mio problema è che dopo aver ereditato DataGridViewColumn
e impostando la proprietà CellTemplate
ad una nuova istanza della mia classe CustomDataGridViewCell
, la cella è di colore grigio, senza contenuti.
La variabile di classe cBox
viene creata un'istanza nel ctor oggetto.
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();
}
Come posso correttamente dipingere il ComboBox
nella cella?
Soluzione
Ho fatto abbastanza semplice cambiamento che consente di risolvere il mio problema.
Ho dovuto correggere le coordinate sia relativo alla finestra invece del DataGridView
, chiamare Controls.Add()
per la forma possessore, e riposizionare il controllo di fronte 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();
}