清除TextBox时出现未处理的异常

时间:2012-11-10 11:46:30

标签: c# winforms

  

可能重复:
  Why am I getting a FormatException was unhandled error?

我是C#和Stack Overflow的新手,所以如果这个问题不合适(或在错误的地方),请随时编辑或删除它。

我已经制作了一个简单的计算器,但是我遇到了一个问题:当我清除其中一个文本框以输入另一个数字时,一条消息显示“未处理的异常发生”并带有退出选项或继续。每次清除texbox时,如何停止显示此消息?

private void button1_Click(object sender, EventArgs e)
{
    int value1 = Convert.ToInt32(textBox1.Text);
    int value2 = Convert.ToInt32(textBox2.Text);
    textBox3.Text = sum(value1, value2).ToString();
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int vlera1 = Convert.ToInt32(textBox1.Text);
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    int vlera2 = Convert.ToInt32(textBox2.Text);
}

private void textBox3_TextChanged(object sender, EventArgs e)
{ }

int sum(int value1, int value2) {
    return (value1) + (value2);
}

2 个答案:

答案 0 :(得分:3)

使用int.TryParse(string s, out int result)代替Convert.ToInt32(string value, int fromBase)
这种情况正在发生,因为您正在尝试将TextBox的空数据转换为Int32

if (int.TryParse(textBox1.Text, out vlera1))
{
    //assign here    
}

答案 1 :(得分:1)

当您尝试将无法转换为FormatException类型的结构的字符串转换为int时,您将收到int。在转换之前,您可以始终使用int.TryParse(string s, out int result)查看string是否能够进行int转换。

示例

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int x = 0; //Initialize a new int of name x and set its value to 0
    if (int.TryParse(textBox1.Text, out x)) //Check if textBox1.Text is a valid int
    {
        int vlera1 = Convert.ToInt32(textBox1.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
    }
    else
    {
        //DoSomething if required
    }
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    int x = 0; //Initialize a new int of name x and set its value to 0
    if (int.TryParse(textBox2.Text, out x)) //Check if textBox2.Text is a valid int
    {
        int vlera2 = Convert.ToInt32(textBox2.Text);  //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
    }
    else
    {
        //DoSomething if required
    }
}

另一种解决方案

您可以始终使用try-catch语句来查看是否从您提供的代码中抛出异常并在需要时执行某些操作

示例

private void textBox1_TextChanged(object sender, EventArgs e)
{
    try
    {
        int vlera1 = Convert.ToInt32(textBox1.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
    }
    catch (Exception EX)
    {
        MessageBox.Show(EX.Message); //(not required) Show the message from the exception in a MessageBox
    }
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
    try
    {
        int vlera2 = Convert.ToInt32(textBox2.Text);  //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
    }
    catch (Exception EX)
    {
        MessageBox.Show(EX.Message); //(not required) Show the message from the exception in a MessageBox
    }
}

注意:try-catch语句包含一个try块,后跟一个或多个catch子句,指定不同异常的处理程序

谢谢, 我希望你觉得这很有帮助:)