c#DataGridView离开事件使Windows窗体没有响应

本文关键字:响应 窗体 Windows 离开 事件 c#DataGridView | 更新日期: 2023-09-27 18:24:39

我在我的c#-4.0 Windows窗体应用程序中遇到了一些奇怪的事情,我不确定是什么原因造成的。基本上,我有一个带有DataGridView和一些文本框的窗体,在我的网格中,我有个离开事件,当用户离开DataGridView时,它会选择Rows[0].Cells[0]

现在,如果我单击网格中的一个单元格,编辑该单元格并直接单击到文本框中,则leave事件会正确触发并选择row/cell[0],但此时表单将变得没有响应。

如何使用Visual Studio复制(我使用的是2010 Pro)

  • 创建新的WindowsFormApplication
  • DataGridViewTextBox添加到表单中
  • 现在,在Form1_Load事件中添加以下代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable dtTmp = new DataTable("temp");
        dtTmp.Columns.Add("col 1", typeof(String));
        dtTmp.Columns.Add("col 2", typeof(String));
        DataSet dsTmp = new DataSet();
        dsTmp.Tables.Add(dtTmp);
        DataRow dr1 = dsTmp.Tables["temp"].NewRow();
        dr1["col 1"] = "aaa";
        dr1["col 2"] = "12";
        dsTmp.Tables["temp"].Rows.Add(dr1);
        DataRow dr2 = dsTmp.Tables["temp"].NewRow();
        dr2["col 1"] = "bbb";
        dr2["col 2"] = "1234";
        dsTmp.Tables["temp"].Rows.Add(dr2);
        dataGridView1.DataSource = dsTmp;
        dataGridView1.DataMember = "temp";
        dataGridView1.Refresh();
    }
    

接下来,为DataGridView1创建一个Leave事件,并添加以下代码:

private void dataGridView1_Leave(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Count > 0)
    {
        dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
    }
}

调试并执行以下步骤:

  1. 单击第1列第二行中包含"bbb"的单元格
  2. 在该单元格中键入其他内容
  3. 在不点击回车、空格、制表符、向下或向右箭头的情况下,单击您添加到表单中的文本框

现在尝试关闭窗体,它不会关闭。

我的dataGridView1.CurrentCell线路出了什么问题?如果选择并编辑第一行,表单会很好地关闭,但如果是第二行,则不会关闭。

c#DataGridView离开事件使Windows窗体没有响应

不确定它是如何干扰的,但Leave事件正在干扰一些东西。通常我的解决方法是,尝试在离开事件之后运行代码

void dataGridView1_Leave(object sender, EventArgs e) {
  this.BeginInvoke(new Action(() => {
    if (dataGridView1.Rows.Count > 0) {
      dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
    }
  }));
}