[英]Comparing two text boxes
我有3個重要的文本框。 一個是Total,另外兩個是最小和最大。 我希望最小和最大的值如果小於或大於其文本中的當前值,則替換為總計中的值。
但是我收到一個錯誤“輸入字符串的格式不正確”,但我無法弄清楚它出了什么問題。
嘗試將其更改為TryParse,但隨后出現錯誤,我無法對bool和bool使用“>”。 也嘗試使用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;
}
您是“多人在線”綜合症的受害者。 在這里沒有任何收獲,而是您松散了一些東西(當然是最少的),因為您兩次轉換了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;
“輸入字符串的格式不正確”是由於任何文本框中的值為空。
一種解決方案是在比較之前檢查空值。 你可以寫
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.