2013-02-03 506 views
0

我想比較兩個文本框,看看他們是空的,但我得到一個異常錯誤:如何比較兩個文本框?

Input string was not in a correct format

代碼:

private void btncalc_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     int ina= int.Parse(txttea.Text); 
     int inb= int.Parse(txtcoffee.Text); 
     int inc = 0, ind = 0; 
     if (this.txttea.Text == "" && this.txtcoffee.Text == "") // this not working 
     { 
      MessageBox.Show("select a item"); 
      txttea.Focus(); 
     } 
     if (cbxwithoutsugar.Checked) 
     { 
      inc = (ina * 20); 
     } 
     else 
     { 
      inc = (ina * 8); 
     } 
     if (cbxcoldcoffee.Checked) 
     { 
      ind = (inb * 10); 
     } 
     else 
     { 
      ind = (inb * 5); 
     } 
     txtamount.Text = (Convert.ToInt32(inc) + Convert.ToInt32(ind)).ToString(); 
    } 
    catch (Exception a) 
    { 
     MessageBox.Show(a.Message); 
    } 
} 
+0

'txttea.Text'和'txtcoffee.Text'的值是什麼? –

+0

檢查你的txttea.Text和txtCoffee.Text是否是數字。 –

+0

iswanto san:它的一個數字 – raneena

回答

0

我有一種感覺,行要表示爲'不工作'不是問題,但整數解析是。該異常不是可以從邏輯測試中拋出的異常,而是可以從格式錯誤的整數解析中拋出的異常。嘗試註釋解析行並查看錯誤是否仍然存在。

2

你應該第一檢查文本輸入框是空的,只有然後嘗試獲得的值。
此外,使用String.IsNullOrEmpty這樣的:

if (String.IsNullOrEmpty(txttea.Text) || String.IsNullOrEmpty(txtcoffee.Text)) 
    { 
     MessageBox.Show("select a item"); 
     txttea.Focus(); 
    } 
    int ina= int.Parse(txttea.Text); // See comment below about TryParse 
    int inb= int.Parse(txtcoffee.Text); 
    int inc = 0, ind = 0; 

此外,使用TryParse,而不是解析(和修剪始終是一個好主意,以避免或空格):

int ina; 
if (!Int32.TryParse(txttea.Text.Trim(), out ina)) 
{ 
    MessageBox.Show("Value is not a number"); 
} 
0

起初你正在解析文本框的文本。然後再次檢查它們的文本值是否爲null。它不是多餘的嗎?

如果文本區域中的文本不是數字,那麼應該有解析異常。它會顯示在消息框中。我想你可以嘗試把一些日誌語句引用分析整數的值。

2

嘗試使用的TryParse方法,因爲如果那裏有一個空格你的代碼失敗, 用的TryParseü不需要的try-catch,只是兩個整數比較爲零,如:

int ina =0 , inb =0; 

int.TryParse(txttea.Text, out ina); 
int.TryParse(txtcoffee.Text, out inb); 

if (ina == 0 && this.inb == 0) // this not working 
{ 

} 
1

我建議您在預期數字時使用NumericUpDown而不是TextBox。這樣您就可以使用Value來獲取咖啡和茶的數量。

private void btncalc_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     int ina= numtea.Value; 
     int inb= numcoffee.Value; 
     int inc = 0, ind = 0; 
     if (ina == 0 && inb == 0) // this not working 
     { 
      MessageBox.Show("select a item"); 
      numtea.Focus(); 
     } 
     if (cbxwithoutsugar.Checked) 
     { 
      inc = (ina * 20); 
     } 
     else 
     { 
      inc = (ina * 8); 
     } 
     if (cbxcoldcoffee.Checked) 
     { 
      ind = (inb * 10); 
     } 
     else 
     { 
      ind = (inb * 5); 
     } 
     txtamount.Text = (inc + ind).ToString(); 
    }  
} 

這是一個很好的userfriendly解決方案。