Cancel Key before it is shown in NumericUpDown

47 Views Asked by At

When I type a key inside a NumericUpDown, it is shown even if I cancel it, no matter which Key event I put it into.

I tried cancelling the key in all those events: events

It does cancel but I always see it for a second before it changes.

1

There are 1 best solutions below

1
Olivier Jacot-Descombes On BEST ANSWER

I could achieve this requirement by simply clearing the Text property of the NumericUpDown instead of suppressing the third key:

private void NumericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    if (numericUpDown1.Value >= 10 && 
        e.KeyData is >= Keys.D0 and <= Keys.D9 or
                     >= Keys.NumPad0 and <= Keys.NumPad9) {

        numericUpDown1.Text = "";
    }
}

Maybe you will have to check for additional conditions like leading zeroes, depending on the exact requirement.

Oh sorry, You want VB. Please, wait a moment...

... here is a VB version:

Private Sub NumericUpDown1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
    If numericUpDown1.Value >= 10 AndAlso
        (e.KeyData >= Keys.D0 AndAlso e.KeyData <= Keys.D9 OrElse
         e.KeyData >= Keys.NumPad0 AndAlso e.KeyData <= Keys.NumPad9) Then

        numericUpDown1.Text = ""
    End If
End Sub

It also seems like e.SuppressKeyPress = True is working in KeyDown.