输入字符串格式不正确c#error

Kao*_*oru 1 c# ms-access winforms

我创建了一个应用程序,其中的信息基于我在数据库中的内容.

当用户键入数据库中存在该代码的代码时,信息将会出现并填满剩余的文本框.

这是我的数据库:

在此输入图像描述

这是我输入" SM0001"时程序的屏幕截图.

在此输入图像描述

请注意,在"产品代码文本框"中输入" SM0001 ","数量文本框","描述文本框","子文本框"和"总文本框"之前是空的.

当我在"产品代码"文本框中键入" SM0001 "时,它会显示属于我输入的代码的所有数据.

注意:数据库中的价格是程序中的子总计

这是我的问题:当我输入" SM0002 "时,在"产品代码文本框"中(我输入的代码不在数据库中,产品代码只在数据库中有" SM0001 "),程序停止并给了我错误" 输入字符串格式不正确",这里指出:

price = Convert.ToDecimal(this.numericTextBox2.Text);
Run Code Online (Sandbox Code Playgroud)

这是必要的代码:

private void textBox_TextChanged(object sender, EventArgs e)
        {
            UpdatePrice(sender, e);
        }

private void UpdatePrice(object sender, EventArgs e)
        {
            decimal quantity = 0;
            decimal price = 0;
            int total = 0;

            if (numericTextBox1.TextLength == 6)
            {
                this.numericUpDown1.Enabled = true;

                quantity = Convert.ToInt32(this.numericUpDown1.Value);
                price = Convert.ToDecimal(this.numericTextBox2.Text);
                total = Convert.ToInt32(quantity * price);

                if (numericUpDown1.Value > 0)
                {
                    this.numericTextBox3.Text = total.ToString();
                }
            }

            else if (numericTextBox1.TextLength != 6)
            {
                this.numericUpDown1.Enabled = false;

                this.textBox5.Text = "";
                this.numericUpDown1.Value = 0;
                this.numericTextBox2.Text = "";
                this.numericTextBox3.Text = "";
            }

            else
            {
                quantity = 0;
                price = 0;
                total = 0;

                MessageBox.Show("There is no data based on your selection", "Error");
            }
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

"产品代码文本框为NumericTextBox1","Sub Total text-box为NumericTextBox2","Total text-box为NumericTextBox3"

小智 5

如果你的例外在这里

price = Convert.ToDecimal(this.numericTextBox2.Text);
Run Code Online (Sandbox Code Playgroud)

并且您的产品代码SM0002不存在,那么这意味着您正在解析不存在的值.所以在那种情况下你有一些处理机制.

使用TryParse,您可以使用它来处理任何不可解析的值并返回所需的值.您可以使用此方法:

private double ParseDouble(string value)
{
  double d=0;
  if(!double.TryParse(value , out d))
  {
      return 0;
  }
  return d;
}
Run Code Online (Sandbox Code Playgroud)

所以你的代码看起来应该是需要转换的地方.

var price = ParseDouble(numericTextBox1.Text);
Run Code Online (Sandbox Code Playgroud)