Handle NumericUpDown value change events in C#


The post Make a NumericUpDown use decimal values in C# shows how you can make a NumericUpDown control display decimal values.

When the user clicks a NumericUpDown control’s arrows or presses the up or down arrow key while the control has focus, the control raises a ValueChanged event to let the program know that its value has changed. Unfortunately that event doesn’t fire if the user types a number into the control.

To detect numbers typed into the control, the program can catch the control’s KeyUp event. This example uses the following code to catch the ValueChanged and KeyUp events.

// Occurs when the user clicks an arrow.
private void nudScale_ValueChanged(object sender, EventArgs e)

// Occurs when the user presses a key.
private void nudScale_KeyUp(object sender, KeyEventArgs e)

When the program catches these events, it uses the form’s Refresh method to make the following Paint event handler execute.

// Draw an ellipse.
private void Form1_Paint(object sender, PaintEventArgs e)
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    // Get the ellipse's size as a fraction
    // of the form's width and height.
    float width = (float)(ClientSize.Width * nudScale.Value);
    float height = (float)(ClientSize.Height * nudScale.Value);

    // Draw the ellipse.
    float x = (ClientSize.Width - width) / 2;
    float y = (ClientSize.Height - height) / 2;
    e.Graphics.DrawEllipse(Pens.Red, x, y, width, height);

This code draws an ellipse with radius determined by the value in the nudScale NumericUpDown control.

Note that the NumericUpDown control will not let the user enter an invalid value. If the user presses a non-numeric key such as A or $, the control ignores it.

The control also will not allow a value that is not between its Minimum and Maximum properties. For example, suppose Minimum = 0 and Maximum = 9. Then if the user selects the control’s text and presses 9, the control sets its value to 1.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in controls, mathematics and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *