Search code examples
c#wpftryparseintegerupdown

How can I use int.TryParse in comparison instruction C# WPF?


I have two IntegerUpDown Controls, and I need to compare in the MouseLeave_Event , I used int.Parse but when I tried this code I got an exception:

   if (int.Parse(minUpdown.Text.ToString()) < 
   int.Parse(maxUpdown.Text.ToString()))
                    {
                      // do something
                    }

Exception:

Input string was not in a correct format

I have searched in Stackoverflow for a solution to avoid this exception, I saw that the best solution is using int.TryParse, but I don't know how can I use it in comparison instruction that returns boolean.

The scenario that should be applied is like this:

  • I have already an IntegerUpdown_MouseLeave_Event and the code that I have posted is mentioned in the event, so the integerUpdown controls could be empties or can have a value, so if the user tries to enter a character ( not a number ) for example a in the IntegerUpDown and this IntegerUpDown have an old value for example 3, so when he moves the mouse outside the control, the IntegerUpDown should take 3 instead of the character entered by the user without showing any message or any exception.

Note: I wouldn't like to use minUpdown.Value in this case for some reason because the value that I got when the event is fired is the old value, not the value in real-time.


Solution

  • The answer for the first question 'How to use TryParse and compare the values' looks like this:

    int.TryParse(minUpdown.Text?.ToString(), out var min);
    int.TryParse(maxUpdown.Text?.ToString(), out var max);
    
    if (min < max)
    {
        // do something
    }
    

    TryParse returns a boolean which tells if the try was performed with success or not.

    Now, if you want your view to replace incorrect value with a last correct value you need to preserve it in some field and update if needed for example:

    private int lastMinValue;
    private int lastMaxValue;
    
    private void IntegerUpdown_MouseLeave_Event(object source, EventArgs args)
    {
        // use last value as a default for min and max
        int min = lastMinValue;
        int max = lastMaxValue;
    
        // try to update min and max
        if (int.TryParse(minUpdown.Text?.ToString(), out min))
        {
            lastMinValue = min;
        }
        if (int.TryParse(maxUpdown.Text?.ToString(), out max))
        {
            lastMaxValue = max;
        }
    
        if (min < max)
        {
            // do something
        }
    }