简体   繁体   中英

Comparing two text boxes

I have 3 textboxes that are important. One is Total, the other two are smallest and largest. I want the smallest and largest to get replaced by the value in Total if it is smaller or larger than the current value in its text.

But I am getting an error "Input string was not in correct format" but I can't figure out what is wrong with it.

Tried changing it to TryParse but then it gives me the error that I can't use ">" for bool and bool. Also tried using Math.Min instead but it was giving me an error and I wasn't sure how to fix that.

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;
        }

You are a victim of the 'all-in-one-line' syndrome. Nothing to gain here, instead you loose something (minimal of course) because you convert the txtTotal field two times. Also, NEVER use Convert.XXXX or decimal.Parse() trying to convert user input in a numeric value. Always use TryParse.

So:

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;

"Input string was not in correct format" is due to empty values in any of the textboxes.

One solution is to check for empty values before comparison. You can write

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;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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