J'ai créé des classes de colonnes personnalisées (DataGridViewButtonControlColumn) et des classes de cellules (ButtonControlCell) pour contenir les contrôles System.Windows.Forms.Button. Les boutons sont ajoutés aux colonnes et affichés correctement. Avant de définir le bouton comme valeur d'un ButtonControlCell, j'attache un gestionnaire d'événements pour "Click". Mais ce gestionnaire n'est pas appelé quand un bouton est cliqué.L'événement de clic de bouton ne se déclenche pas à partir de DataGridViewCell personnalisé
J'ajoute le bouton aux contrôles de DataGridView dans la fonction Paint surchargée.
Y at-il des étapes spécifiques que je dois suivre pour enregistrer le bouton avec DataGridView?
code:
public class ButtonControlCell : DataGridViewTextBoxCell
{
.
.
.
protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
if (btnVal != null)
{
btnVal.Size = new System.Drawing.Size(80, 20);
btnVal.Location = cellBounds.Location;
this.DataGridView.Controls.Add(btnVal);
}
}
.
.
.
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
// This is not called when the button is clicked (which is correct I guess)
base.OnMouseClick(e);
if (btnVal != null)
{
btnVal.PerformClick();
}
}
.
.
}
Dans la mise en œuvre:
private void AddButtonCell(string sText, EventHandler oEh, DataGridViewButtonColumn oClm, DataGridView dgvParent, int iRow, int iColumn)
{
Button btnTemp = new Button();
btnTemp.Height = 20;
btnTemp.Width = 60;
btnTemp.Anchor = AnchorStyles.Top;
btnTemp.Text = sText;
btnTemp.Click += new EventHandler(btnTemp_Click);
btnTemp.Tag = new Point(iRow, iColumn);
Controls.Add(btnTemp);
dgvParent.Rows[iRow].Cells[iColumn].Value = btnTemp;
}
void btnTemp_Click(object sender, EventArgs e)
{
Button btnSender = (Button)sender;
DataGridViewRow r = dgvResults.Rows[((Point)btnSender.Tag).X];
TagInfo oRet = new TagInfo((string)r.Cells[iTitleColIndex].Value, (string)r.Cells[iArtistColIndex].Value,
(string)r.Cells[iAlbumColIndex].Value);
oRet.imgAlbumArt = (System.Drawing.Image)r.Cells[iArtColIndex].Tag;
oParent.TagWithInfo(oRet, true);
}
J'utilisais un DataGridViewButtonColumn mais il ne se comportait pas comme je le souhaitais. Le contrôle est redimensionné pour remplir la cellule et je n'ai pas pu trouver une propriété pour l'empêcher. BTW, j'utilise temporairement un DataGridViewLinkColumn, jusqu'à ce que je puisse comprendre comment déclencher l'événement click – Gayan