2017-02-19 85 views
0

我有十进制输入一个问题,这里是我使用的是按钮的代码单击十进制值给出错误

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时,单击它显示了textbox6无效值 当第二个与PPrice 28点击,它通常继续

我该如何解决,因此它会接受小数?

UPDATE

前面的代码不是问题,真正的问题是这段代码,它显示了当计算是对文本本身所以这里没有作出错误的完整代码

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

什么类型textBox6的是什么? – AlirezaJ

+1

这不是关于显示“小数”,因为在这两种情况下,赋给'.Text'的值都是一个字符串。请慢慢调试,并确实看到预期的函数被调用。当你说“无效的价值”时,你的意思是什么? –

+0

好的,单击按钮,信息会进入文本框,除了小数点之外会出现“无效”,然后单击按钮将它们添加到列表视图,这是我在调试中得到的结果 在mscorlib中发生未处理的类型为“System.FormatException”的异常.dll 附加信息:输入字符串格式不正确。 –

回答

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 
{ 
} 
+0

谢谢,测试过,它工作的很好,解决了我的问题 –