I've got a DataGridView
including a DataGridViewButtonColumn
. The user should be able to use the button directly so I set EditMode
to EditOnEnter
. But, the first click didn't fire the Click
event - It seems like the first click selects/focus the row/column?
So I tried to use the CellClick
Event:
Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick
Dim validClick = (e.RowIndex <> -1 And e.ColumnIndex <> -1)
If (TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewButtonColumn And validClick) Then
dgv.BeginEdit(True)
CType(dgv.EditingControl, Button).PerformClick()
End If
End Sub
But this solution didn't work either. EditingControl
always throws a NullReferenceException
.
Any ideas?
I do not think there is a specific event available to handle when a DataGridViewButtonColumn
cell is clicked. The DataGridView
’s Cell_Clicked
and CellContentClicked
events get fired.
I was not able to get the delay of clicking into the DataGridView
once then having to click again to fire the button. When I clicked on the DataGridView
button cell, the Cell_Clicked
event was immediately fired. Changing the DataGridView
’s EditMode
made no difference. The code below simply identifies WHICH cell was clicked from the Cell_Clicked
event. If the cell clicked was a button column (1 or 2), then I call a created method ButtonHandler
to handle which button was pressed and to continue on to the correct button method. Hope this helps.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 1 || e.ColumnIndex == 2) {
// one of the button columns was clicked
ButtonHandler(sender, e);
}
}
private void ButtonHandler(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == 1) {
MessageBox.Show("Column 1 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked");
// call method to handle column 1 button clicked
// MethodToHandleCol1ButtonClicked(e.RowIndex);
}
else {
MessageBox.Show("Column 2 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked");
// call method to handle column 2 button clicked
// MethodToHandleCol2ButtonClicked(e.RowIndex);
}
}