数字输入的输入字符串格式不正确
本文关键字:格式 不正确 字符串 输入 数字输入 | 更新日期: 2023-09-27 18:34:08
我创建了一个应用程序,其中我键入的产品代码基于数据库。
但是我有一个问题,当数据库中的产品代码与我键入的内容不匹配时。它给了我错误:
Input string was not in a correct format
它指向:
price = Convert.ToDecimal(this.numericTextBox2.Text);
假设我在数据库中有这样的数据:
+--------------+-------------+-----------+|产品代码 |描述 |小计 |+--------------+-------------+-----------+|SM0001 |测试 | 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 是我在其中放置产品代码的文本框。
在我上面的代码中,当Product Code
命中 6 个字母时,程序会根据数据库显示price
和其余部分。但是,当程序无法根据Product Code
找到price
是什么时,它给出了错误。当Product Code
命中6个字母时,程序将检查已输入的product code
是否与数据库匹配,如果匹配,程序将根据输入的product code
显示所有信息。
已编辑:
程序仍然认识到,只要输入的product code
(numericTextBox1.Text(等于6,就必须显示price
。当我输入SM0001
时,它没有显示错误,因为该SM0001
中有price
.但是当我尝试将数据库中没有数据但numericTextBox1.Text
等于 6 的SM0002
时,程序被迫显示一个没有price
属于输入product code
(SM0002( 的price
。
我想要的是当numericTextBox1.Text
等于 6 个字母时,它会查看数据库中的信息,如果有与数据库相同的product code
(匹配(,程序将显示属于该代码的其余信息<- 这是完成并解决的。
当我输入数据库中没有数据SM0002
时,它给出了错误。
每当数字文本框1点击6个字母时,numericTextBox2就会出现。当数字文本框1与数据库匹配时,它将显示所有信息。现在,我的问题是当数字文本框1与数据库不匹配时,它给出了错误
它必须在行中
price = Convert.ToDecimal(this.numericTextBox2.Text);
检查您输入的内容 numericTextBox2
.
编辑
您可以尝试使用此代码来检测您是否具有有效号码:
if (Decimal.TryParse(this.numericTextBox2.Text, out price))
{
total = Convert.ToInt32(quantity * price);
}