执行计算时无法解决此异常

Unable to solve this exception when performing calculation

我在文本框 2 中有这段代码,它将文本框 1 和 2 的值相乘,将结果添加到文本框 3:

private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBox3.Text = Convert.ToString(Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text));
        }

当我通过这个在数据库中插入数据时

code private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Insert into Receipts(Qty,ItemName,Price,Amount) values('" + textBox2.Text + "','" + textBox4.Text + "','" + textBox1.Text + "','" + textBox3.Text + "')";
            cmd.ExecuteNonQuery();

            con.Close();
            this.receiptsTableAdapter.Fill(this.shopDataSet.Receipts);
            textBox4.Clear();
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();


            //MessageBox.Show("Data Inserted !");
        }

我在 textBox2.Clear() 上遇到错误; (异常处理但数据插入成功) 没有这个程序工作正常,

textBox4.Clear();
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

我想清除文本框,我只在 textbox2 上遇到错误,其中包含将文本框 1 和 2 的值相乘的代码,并将结果添加到文本框 3。

谢谢:)

I get error on textBox2.Clear(); ( exceptional handling but data inserts succcessfully ) program is working fine without this,

 textBox4.Clear();
 textBox1.Clear(); // This is the first problem
 textBox2.Clear(); // This is the second problem
 textBox3.Clear();

这个错误的原因是因为事件textBox2_TextChanged。在您尝试使用 Text 属性 执行计算的内部,这失败了,因为 Text 属性 为空并且无法转换它。

 textBox3.Text = Convert.ToString(Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text));

要解决此问题,您可以先检查 Text 属性 是否可以在使用 Int.TryParse Method 和输出变量之前成功解析;仅适用于 C# >= 7.0。例如:

 private void textBox2_TextChanged(object sender, EventArgs e)
 {
    if(int.TryParse(textBox1.Text, out int txt1) && int.TryParse(textBox2.Text, out int txt2))
    {
       textBox3.Text = (txt1 * txt2).ToString();
    }
 }

如果目标版本早于 C# 7.0,您可能会使用的另一个版本:

 private void textBox2_TextChanged(object sender, EventArgs e)
 {
    int txt1;
    int txt2;
    if(int.TryParse(textBox1.Text, out txt1) && int.TryParse(textBox2.Text, out txt2))
    {
       textBox3.Text = (txt1 * txt2).ToString();
    }
 }

正如其他人所说,您遇到的问题与 textBox2_TextChanged 有关,每次您在 textBox2 中更改任何内容时都会调用此 void

在我看来,您应该检查您的文本框以确保它们不为空,然后尝试解析您的整数。

这里有一些可以帮助您入门的东西。

https://dotnetfiddle.net/lyNnQY