繁体   English   中英

比较两个文本框

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM