简单的C#Windows应用程序 - 无论如何都会执行Catch语句

0 c# validation textbox try-catch

这是涉及的事件处理程序的代码:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                seed = Convert.ToInt32(this.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Input string is not a sequence of digits.");
            }
            catch (OverflowException)
            {
                MessageBox.Show("The number cannot fit in an Int32.");
            }

        }
Run Code Online (Sandbox Code Playgroud)

它应该确保用户不会Int32在文本框中键入任何允许的数字,但是每次尝试在框中键入ANYTHING时都会执行第一个catch语句.我环顾四周但似乎无法弄明白为什么......

Jus*_*ner 5

可能是因为this.Text没有从输入框中读取,而是从中定义了处理程序的类.

我相信你想要的是:

try
{
    seed = Convert.ToInt32(((TextBox)caller).Text);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,它试图解析表格标题. (2认同)