我有十进制输入问题,这是我在按钮上使用的代码
private void button6_Click_1(object sender, EventArgs e)
{
string PName = "كريب دجاج شاورما";
string PPrice = "20.50";
string PQty = "1";
textBox1.Text = PName;
textBox6.Text = PPrice;
textBox2.Text = PQty;
textBox5.Text = "0";
}
private void button7_Click_1(object sender, EventArgs e)
{
string PName = "كريب تشيكن شريمبو";
string PPrice = "28";
string PQty = "1";
textBox1.Text = PName;
textBox6.Text = PPrice;
textBox2.Text = PQty;
textBox5.Text = "0";
}
单击PPrice 20.50时单击它在文本框6中显示无效值 当点击PPrice 28的第二个时,它会正常继续
我该如何修复它以便接受小数?
更新
以前的代码不是问题,真正的问题是这个代码,它显示的错误不是在文本框本身进行计算时所以这里是完整的代码
private void button6_Click_1(object sender, EventArgs e)
{
string PName = "كريب دجاج شاورما";
string PPrice = "20.50";
string PQty = "1";
textBox1.Text = PName;
textBox6.Text = PPrice;
textBox2.Text = PQty;
textBox5.Text = "0";
}
private void button7_Click_1(object sender, EventArgs e)
{
string PName = "كريب تشيكن شريمبو";
string PPrice = "28";
string PQty = "1";
textBox1.Text = PName;
textBox6.Text = PPrice;
textBox2.Text = PQty;
textBox5.Text = "0";
} private void textBox3_TextChanged(object sender, EventArgs e)
{
Multiply();
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
int first = 0;
int second = 0;
if (Int32.TryParse(textBox5.Text, out second) && Int32.TryParse(textBox6.Text, out first))
textBox3.Text = (first + second).ToString();
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
int first = 0;
int second = 0;
if (Int32.TryParse(textBox5.Text, out second) && Int32.TryParse(textBox6.Text, out first))
textBox3.Text = (first + second).ToString();
}
答案 0 :(得分:2)
您收到错误是因为您尝试将带小数点的字符串转换为整数。
您有以下代码:
string PPrice = "20.50";
textBox6.Text = PPrice;
然后你有这个代码:
int first = 0;
int second = 0;
if (Int32.TryParse(textBox5.Text, out second) && Int32.TryParse(textBox6.Text, out first))
textBox3.Text = (first + second).ToString();
Int.TryParse(textbox6.Text, out first
失败并返回false
,因为20.50
无法转换为integer
。
您需要将值解析为十进制,如果成功,则继续:
decimal pPrice;
if (decimal.TryParse(textbox6.Text, out pPrice))
{
// do what you need
}
else
{
}