how to validate numericupdown when value change (and not lost focus)

angel picture angel · Jun 28, 2013 · Viewed 11.1k times · Source

I have a NumericUpDown and I need when value change (and not lostfocus) do a new calculation

if i put my code in event ValueChanged this work when focus is lost

if i put my code in KeyPress then if number is not enter by keyboard (example copy a number and paste it) it doesn't work

then what event do i need use?

and if this is keypress i need concatenate the numeric value more the key pressed convert all this to string and convert it to decimal, and do the calculate, but it does not work if key pressed is not a number (example backspace)

Answer

Andrea picture Andrea · Jun 29, 2013

You can use KeyUp event to check direct editing and paste operations with CTRL+V.

Then you can listen to MouseUp event to check paste operations with right mouse button (context menu).

In this sample code a MessageBox is shown if user inputs a number greater than 9:

private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
    if (numericUpDown1.Value >= 10){
       numericUpDown1.Value = 0;
       MessageBox.Show("number must be less than 10!");
    }
}

private void numericUpDown1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right) {
       if (numericUpDown1.Value >= 10){
           numericUpDown1.Value = 0;
           MessageBox.Show("number must be less than 10!");
       }
    }
}