2016-01-23 138 views
1

我有3個重要的文本框。一個是Total,另外兩個是最小和最大的。如果小於或大於其文本中的當前值,我希望最小和最大值被Total中的值替換。比較兩個文本框

但我得到一個錯誤「輸入字符串格式不正確」,但我無法弄清楚它有什麼問題。

嘗試將其更改爲TryParse,但它給了我錯誤,我不能使用「>」布爾和布爾。也嘗試使用Math.Min,而不是它給了我一個錯誤,我不知道如何解決這個問題。

if (Convert.ToDecimal(txtTotal.Text) < Convert.ToDecimal(txtSmallestInvoice.Text)) 
     { 
      txtSmallestInvoice.Text = txtTotal.Text; 
     } 

if (Convert.ToDecimal(txtTotal.Text) > Convert.ToDecimal(txtLargestInvoice.Text)) 
     { 
      txtLargestInvoice.Text = txtTotal.Text; 
     } 
+0

的'Text'可以'string.Empty',所以轉換可能會失敗。 –

+0

你有任何語言(國際化)問題。 –

+1

@Alex您不應該比較'TryParse'的結果,該結果返回'Bool'指示解析是否成功。而是比較'out'參數值。 – tchelidze

回答

1

你是「全合一」綜合徵的受害者。這裏沒有什麼可以獲得的,相反,當你轉換txtTotal字段兩次時,你會放鬆一些東西(當然最少)。此外,切勿使用Convert.XXXX或decimal.Parse()嘗試將用戶輸入轉換爲數字值。始終使用TryParse。

所以:

decimal total; 
decimal minimum; 
decimal maximum; 
if(!decimal.TryParse(txtTotal.Text, out total)) 
{ 
    MessageBox.Show("Not a valid total value"); 
    return; 
} 

// If the textbox doesn't contain a number then set the 
// minimum to the max value for decimals 
// (in this way the total will be always lower 
if(!decimal.TryParse(txtSmallestInvoice.Text, out minimum)) 
    minimum = decimal.MaxValue; 

// the same logic for maximum but reversed 
if(!decimal.TryParse(txtLargestInvoice.Text, out maximum)) 
    maximum = decimal.MinValue; 

if(total < minimum) 
    txtSmallestInvoice.Text = txtTotal.Text; 
if(total > maximum) 
    txtLargestInvoice.Text = txtTotal.Text; 
+0

它的工作最大,但沒有改變的最小值(它保持空白),我不明白爲什麼 – Alex

+0

是的,在空白文本的情況下,這將返回零。需要修復 – Steve

0

「輸入字符串格式不正確」是由於任何文本框中的值爲空。

一個解決方案是在比較之前檢查空值。你可以寫

if (txtTotal.Text != "" && txtSmallestInvoice.Text != "" && txtLargestInvoice.Text != "") 
{ 
    if (Convert.ToDecimal(txtTotal.Text) < Convert.ToDecimal(txtSmallestInvoice.Text)) 
     { 
      txtSmallestInvoice.Text = txtTotal.Text; 
     } 

if (Convert.ToDecimal(txtTotal.Text) > Convert.ToDecimal(txtLargestInvoice.Text)) 
     { 
      txtLargestInvoice.Text = txtTotal.Text; 
     } 
}