【问题标题】:Manually fire button click event in DataGridView在 DataGridView 中手动触发按钮单击事件
【发布时间】:2017-05-31 05:11:50
【问题描述】:

我有一个DataGridView,包括一个DataGridViewButtonColumn。用户应该可以直接使用按钮,所以我将EditMode 设置为EditOnEnter。但是,第一次点击没有触发 Click 事件 - 似乎第一次点击选择/聚焦行/列?

所以我尝试使用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

但是这个解决方案也不起作用。 EditingControl 总是抛出 NullReferenceException

有什么想法吗?

【问题讨论】:

  • 看看答案here。这是一个 c# 问题,但是答案转换为 VB.NET,因此您应该能够从中挑选出一些内容。
  • 谢谢,我看到了这个问题。问题不在于运行任何函数/方法/事件 - 问题在于,第一次单击始终聚焦该行并且即使 DataGridView EditMode 为 EditOnEnter 也不会触发 CellClick/CellContentClick 事件。有什么解决方法吗?每当用户单击 DataGridViewButtonColumn 时,DataGridViewButtonColumn 后面的代码都会触发...

标签: vb.net datagridview click datagridviewbuttoncolumn


【解决方案1】:

我认为单击DataGridViewButtonColumn 单元格时没有可处理的特定事件。 DataGridViewCell_ClickedCellContentClicked 事件被触发。

我无法延迟点击DataGridView 一次,然后必须再次点击才能触发按钮。当我点击DataGridView 按钮单元格时,Cell_Clicked 事件立即被触发。更改DataGridViewEditMode 没有任何区别。下面的代码简单地标识了从Cell_Clicked 事件中单击了哪个单元格。如果单击的单元格是按钮列(1 或 2),那么我调用创建的方法 ButtonHandler 来处理按下了哪个按钮并继续使用正确的按钮方法。希望这会有所帮助。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2020-12-28
    • 2015-10-18
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多