2

可能重复:
为什么我收到 FormatException 未处理错误?

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

我做了一个简单的计算器,但我有一个问题:当我清除一个文本框以输入另一个数字时,一条消息显示“发生未处理的异常”,可选择退出或继续。每次清除 texboxes 时,如何停止显示此消息?

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);
}
4

2 回答 2

3

使用int.TryParse(string s, out int result)而不是Convert.ToInt32(string value, int fromBase)
发生这种情况是因为您试图将 的空数据转换TextBoxInt32.

if (int.TryParse(textBox1.Text, out vlera1))
{
    //assign here    
}
于 2012-11-10T11:51:25.160 回答
1

当您FormatException尝试将无法转换为 struct 类型的字符串转换intint. 在进行转换之前,您可以随时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 子句组成,这些子句为不同的异常指定处理程序

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

于 2012-11-10T12:34:20.470 回答