3

当页面加载时,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());
}
4

1 回答 1

6

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

protected override void OnShown(EventArgs e) {
  base.OnShown(e);
  dgStation.RowEnter += dgStation_RowEnter;
}

确保从设计器文件中删除当前的 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());
  }
}
于 2012-08-14T12:53:36.930 回答