Question

I have an application in WinForms where I have many controls. These controls represents settings of application and user can save this settings by clicking on a button.

I am trying to resolve a problem with NumericUpDown (I will call it Num) control: Lets say that Num has these properties:

Minimum: 10 Maximum: 60 Step: 1

If a user want to change value, there are two ways how to do that: clicking on arrows (right side of the Num) or manually typing value directly to Num. First way is OK but most most of users are using second way and there is a little problem.

If a user type some value out of the interval for example 1, it is OK because he could continue in typing with 5 so final value is 51 and this is inside the interval. But if he stop typing after value 1, it means he type value out of the interval (1). If he click somewhere out of the Num, value (which is out of the interval) is automatically changed to the closest allowed value (in case of 1, value will be changed to 10).

But he probably will not notice this automatic change so I want to handle it somehow and inform him that he put there invalid value. But this situation is not handled by any event of Num (there is no way how to find out this invalid value he put there - if I try to read value inside ValueChanged event, it reads automatically changed value, not the invalid one).

I know I can add TextChanged event, but there is a problem that if he type some invalid value (5), it can be changed to valid value (by adding 1 so it makes 15).

Do you have any ideas how to resolve this issue? I know this is stupid but this doesn't depend on me, I have to do this and I don't know how.

Was it helpful?

Solution 2

So this is my solution:

I handle TextChanged event and inside this method I assign text to its tag:

Private Sub NUDTextChanged()
    Integer.TryParse(NUD.Text, NUD.Tag)
End Sub

And then:

Private Sub NUD_LostFocus() Handles NUD.LostFocus
    If NUD.Tag < NUD.Minimum Or NUD.Tag > NUD.Maximum Then
        ' show message
    End If
End Sub

Handling Validating event is useless for me because automatic change to allowed value is before validating and this automatic change fires TextChange event so after validating I have new value instead invalid one.

LostFocus is before automatic change so I can easily control if the value is valid or not.

OTHER TIPS

use Lost Focus and instead of setting the minimum at design stage check it with an If statement.

 Private Sub Num_LostFocus(sender As Object, e As System.EventArgs) Handles Num.LostFocus
     If Num.Value < 10 Then MsgBox("Number is incorrect")
 End Sub

alternatively you can probably create a custom control where you can override the event that changes the value to the minimum but i have never tried.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top