gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:47:10 24 4
gpt4 key购买 nike

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

现在,如果我单击我的网格中的一个单元格,编辑该单元格并直接单击文本框,离开事件将正确触发并选择行/单元格 [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. 单击 col 1 中第二行中包含 “bbb” 的单元格。
  2. 在该单元格中输入其他内容。
  3. 不按回车键、空格键、制表符、向下或向右箭头,单击您添加到表单的文本框

现在尝试关闭表单,它没有关闭。

我的 dataGridView1.CurrentCell 行有什么问题?如果您选择并编辑第一行,表单会正常关闭,但如果是第二行则不会。

最佳答案

不确定它是如何干扰的,但是 Leave 事件干扰了某些东西。按照我通常的治疗方法,尝试在 Leave 事件之后运行代码:

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

关于c# DataGridView 离开事件使 Windows 窗体无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com