2017-02-19 83 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

謝謝,測試過,它工作的很好,解決了我的問題 –