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

时间:2013-10-06 06:57:00

标签: c# winforms ms-access

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

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

这是我的数据库:

enter image description here

当我输入“ SM0001”时,以下是我的程序的屏幕截图。

enter image description here

请注意,在“产品代码”文本框中输入“ SM0001 ”之前,请在“数量文本框”,“说明文本框”,“子文本总计”中输入“ SM0001 ”框“和”总文本框“是空的。

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

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

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

price = Convert.ToDecimal(this.numericTextBox2.Text);

以下是必要的代码:

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

有人可以帮我吗?

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

2 个答案:

答案 0 :(得分:5)

如果你的例外在这里

price = Convert.ToDecimal(this.numericTextBox2.Text);

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

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

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

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

var price = ParseDouble(numericTextBox1.Text);

答案 1 :(得分:1)

转换前

将其检查为null或为空 喜欢

if(!string.IsNullOrEmpty(this.numericTextBox2.Text.ToString()))
{
price = Convert.ToDecimal(this.numericTextBox2.Text);
}else
{
price = 0;//or what you want
}