按回车键时转到下一个文本框

匿名
2024-05-14T08:03:48.55+00:00

您好,在我的WinForms应用程序中,我有这个下面的程序,它有助于在按下回车键时转到下一个文本框,但是我在这里遇到了一个问题。 当我在键入内容后按回车键或没有在第一个文本框中键入任何内容时,它将转到下一个文本框。 但是,如果我不小心输入了某些内容并按退格键删除了第一个文本框内容,并且如果我按回车键,那么它不会移动到下一个文本框,请帮助如何解决此问题。

private void Form1_Shown(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in Controls)
                {
                    if (control is TextBox textBox)
                    {
                        textBox.KeyDown += (s, ea) =>
                        {
                            if (ea.KeyCode != Keys.Enter) return;
                            ea.SuppressKeyPress = true;
                            SelectNextControl(ActiveControl, true, true, true, true);
                        };
                    }
                    else if (control is ComboBox comboBox)
                    {
                        comboBox.KeyDown += (s, ea) =>
                        {
                            if (ea.KeyCode != Keys.Enter) return;
                            ea.SuppressKeyPress = true;
                            SelectNextControl(ActiveControl, true, true, true, true);
                        };
                    }
                    else if (control is DateTimePicker dateTimePicker)
                    {
                        dateTimePicker.KeyDown += (s, ea) =>
                        {
                            if (ea.KeyCode != Keys.Enter) return;
                            ea.SuppressKeyPress = true;
                            SelectNextControl(ActiveControl, true, true, true, true);
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Enter Failed:" + ex.Message.ToString(), "Enter",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Note:此问题总结整理于: Go to next text box when enter is pressed

开发人员技术 | Windows 窗体
开发人员技术 | Visual Studio | 其他
开发人员技术 | C#
0 个注释 无注释
{count} 票

接受的答案
  1. Hui Liu-MSFT 48,681 信誉分 Microsoft 外部员工
    2024-05-14T12:18:00.5766667+00:00

    我建议您将 fieldTextBox 的 CausesValidation 属性更改为 false,这将禁止验证和验证事件。 我做了一个测试,效果很好。 测试结果: 最好的问候, Daniel Zhang90644-4231.png90703-4231.gif


    如果回复有帮助,请点击“接受答案”并点赞。

    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    1 个人认为此答案很有帮助。
    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。