[英]Manually fire button click event in DataGridView
I've got a DataGridView
including a DataGridViewButtonColumn
. 我有一个
DataGridView
包括DataGridViewButtonColumn
。 The user should be able to use the button directly so I set EditMode
to EditOnEnter
. 用户应该可以直接使用按钮,因此我将
EditMode
设置为EditOnEnter
。 But, the first click didn't fire the Click
event - It seems like the first click selects/focus the row/column? 但是,第一次单击没有触发
Click
事件-似乎第一次单击选择了/重点放在了行/列上?
So I tried to use the CellClick
Event: 因此,我尝试使用
CellClick
事件:
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
. EditingControl
总是抛出NullReferenceException
。
Any ideas? 有任何想法吗?
I do not think there is a specific event available to handle when a DataGridViewButtonColumn
cell is clicked. 我不认为单击
DataGridViewButtonColumn
单元格时可以处理特定事件。 The DataGridView
's Cell_Clicked
and CellContentClicked
events get fired. 触发
DataGridView
的Cell_Clicked
和CellContentClicked
事件。
I was not able to get the delay of clicking into the DataGridView
once then having to click again to fire the button. 我无法获得一次单击进入
DataGridView
的延迟,然后不得不再次单击以触发该按钮。 When I clicked on the DataGridView
button cell, the Cell_Clicked
event was immediately fired. 当我单击
DataGridView
按钮单元格时,立即触发了Cell_Clicked
事件。 Changing the DataGridView
's EditMode
made no difference. 更改
DataGridView
的EditMode
没什么区别。 The code below simply identifies WHICH cell was clicked from the Cell_Clicked
event. 下面的代码仅标识WHICH单元是从
Cell_Clicked
事件中单击的。 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. 如果单击的单元格是一个按钮列(1或2),那么我将调用一个创建的方法
ButtonHandler
来处理按下了哪个按钮,然后继续使用正确的按钮方法。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.