输入字符串的数字输入格式不正确

时间:2013-10-06 03:48:06

标签: c# winforms

我创建了一个应用程序,其中我为产品代码键入的内容基于数据库。

但是当数据库中的产品代码与我输入的内容不匹配时,我遇到了问题。它给了我错误:

Input string was not in a correct format

指出:

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

假设我在数据库中有这样的数据:

+--------------+-------------+-----------+
| Product Code | Description | Sub Total |
+--------------+-------------+-----------+
| SM0001       | Test        |     50000 |
+--------------+-------------+-----------+

当我在程序中尝试并在产品代码中键入“SM0002”时,显示错误。

注意:当我在程序中输入“产品代码”时,它会显示程序中属于“产品代码”的所有信息

以下是必要的代码:

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

任何人都知道如何解决这个问题?

NumericTextBox1是我放入产品代码的文本框。

在上面的代码中,当price达到6个字母时,程序会显示Product Code,其余的基于数据库。但是,当程序无法找到基于price的{​​{1}}时,它会给出错误。当Product Code点击6个字母时,程序将检查输入的Product Code是否与数据库匹配,如果匹配,程序将根据输入的product code显示所有信息

EDITED

程序仍然认识到,只要输入的product code(numericTextBox1.Text)等于6,就必须显示price。当我输入product code时,它没有显示错误,因为SM0001中有price。但是,当我尝试将SM0001放在数据库中没有数据但SM0002等于6时,程序强制显示numericTextBox1.Text t price属于输入price(SM0002)..

我想要的是当product code等于6个字母时,它会查看数据库中的信息,如果有numericTextBox1.Text与数据库相同(匹配),程序将显示属于该代码的其余信息< - 这已完成并已解决..

当我把product code放在数据库中没有数据时,就会出错。

每当numericTextBox1点击6个字母时,

numericTextBox2就会出现..当numericTextBox1与数据库匹配时,它将显示所有信息。现在,我的问题是当numericTextBox1与数据库不匹配时,它给出了错误

1 个答案:

答案 0 :(得分:0)

必须在

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

检查您输入numericTextBox2的内容。

修改

您可以尝试使用此代码来检测您是否拥有有效数字:

if (Decimal.TryParse(this.numericTextBox2.Text, out price))
{
     total = Convert.ToInt32(quantity * price);
}