Question

J'ai un contrôle ComboBox personnalisé que je veux utiliser dans un DataGridViewCell. J'ai d'abord hérité DataGridViewCell et essaie de passer outre la méthode Paint() pour peindre le ComboBox dans la cellule.

Mon problème est que, après avoir hérité DataGridViewColumn et définissant la propriété CellTemplate à une nouvelle instance de ma classe CustomDataGridViewCell, la cellule est gris sans contenu.

La variable de classe cBox est instancié dans le cteur de l'objet.

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

Comment puis-je peindre correctement le ComboBox dans la cellule?

Était-ce utile?

La solution

J'ai fait changement assez simple qui résout mon problème.

I eu pour corriger les coordonnées d'être par rapport à la fenêtre au lieu de la DataGridView, appeler Controls.Add() pour la forme de la propriété, et repositionner le contrôle en face de la 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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top