在加载时阻止DataGridView RowEnter事件

Laj*_*ker 3 c# winforms

当页面加载时,datagridview将从数据库绑定.

我需要行输入事件来选择行并基于从数据库中检索数据.

但是在加载时它不应该发生.我怎样才能做到这一点 ?

这是我的代码

private void dgStation_RowEnter(object sender, DataGridViewCellEventArgs e)
{
    dgStation.Rows[e.RowIndex].Selected = true;
    int id = Convert.ToInt32(dgStation.Rows[e.RowIndex].Cells[1].Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ech 6

您可以在加载表单后附加有线处理程序,如下所示:

protected override void OnShown(EventArgs e) {
  base.OnShown(e);
  dgStation.RowEnter += dgStation_RowEnter;
}
Run Code Online (Sandbox Code Playgroud)

确保从设计器文件中删除当前的RowEnter处理程序.

或者只使用加载标志:

private bool loading = true;

protected override void OnShown(EventArgs e) {
  base.OnShown(e);
  loading = false;
}

private void dgStation_RowEnter(object sender, DataGridViewCellEventArgs e) {
  if (!loading) {
    dgStation.Rows[e.RowIndex].Selected = true;
    int id = Convert.ToInt32(dgStation.Rows[e.RowIndex].Cells[1].Value.ToString());
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 由于某些原因,这对我不起作用,解决方法是检查DataGrid.Focused = true,然后在数据绑定代码完成后,然后手动调用DataGrid.Focus() - 这样我就有一个事件被触发了. (2认同)