单击编程按钮会引发“System.StackOverflowException”异常

2024-03-03

我在 C#.Net 中编写了一个 WinForms 程序,用于以编程方式单击密码表单中的按钮。

Form1加载并显示Form2作为对话框。

如果 DialogResult 不是 DialogResult.OK,则应用程序将关闭。

到目前为止我有一个按钮单击事件,其编码如下:

 if (txtpass.Text == "")
            {
                MessageBox.Show("You need to enter a password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                txtpass.Focus();
            }
            else
            {
                if (txtpass.Text == "1234")
                {
                    radButton1.DialogResult = DialogResult.OK;
                    radButton1.PerformClick();
                }
                else
                {
                    MessageBox.Show("Password Incorrect", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtpass.Text = "";
                    txtpass.Focus();
                }
            }

I use radButton1.PerformClick();,但是运行该程序会给出以下消息:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

我不确定是什么导致抛出此异常。


Edit不是猜测。告诉按钮从其内部单击自身肯定会导致无限循环。这会导致该方法被一遍又一遍地调用,填满堆栈并导致其溢出。

我的猜测是那个电话PerformClick()导致您发布的当前方法再次被调用,从而导致无限调用循环并导致StackOverflowException.

为了防止这种情况,您需要修复代码中某处的逻辑,以便:

if (txtpass.Text == "1234")

评估为false并且 click 方法不会被一遍又一遍地调用。您可能可以通过设置来实现这一点txtpass.Text = ""就在你让它再次点击自己之前。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

单击编程按钮会引发“System.StackOverflowException”异常 的相关文章

随机推荐