Make a NumericUpDown use decimal values in C#

Datetime:2016-08-22 22:14:05          Topic: C#           Share

Most developers know that the NumericUpDown control lets a user select a number, but few know that it can handle decimal values in addition to integers.

The control’s DecimalPlaces property determines the number of digits after the decimal that the control allows. The Increment property determines the amount the value changes when the user clicks the up or down arrows. By default Increment is 1. If you set DecimalPlaces greater than 0, you may want to set Increment to a value less than 0 to make it easier for the user to select decimal values. You may also want to change Minimum and Maximum to restrict the values to a reasonable range.

Note that this control can be awkward if the user must select decimal values within a large range and the control allows many digits after the decimal point. For example, if Minimum = 0 , Maximum = 1000 , DecimalPlaces = 3 , and Increment = 0.001 , then the user can’t easily select the value 987.654 by clicking the up and down arrows. The user can still click and drag to select the value and then type in a new value, but the arrow keys aren’t very useful.

This example lets the user select decimal values between 0 and 1 with DecimalPlaces = 2 . The program then draws a ellipse with width and height that are equal to the selected number times the form’s width and height.

When the program starts, it uses the following code to prepare the NumericUpDown control named nudScale .

// Redraw on resize.
private void Form1_Load(object sender, EventArgs e)
    ResizeRedraw = true;
    nudScale.Minimum = 0;
    nudScale.Maximum = 1;
    nudScale.DecimalPlaces = 2;
    nudScale.Increment = 0.01m;

When the user clicks the control’s up or down button, the following code makes the form redraw itself.

// Redraw.
private void nudScale_ValueChanged(object sender, EventArgs e)

Finally the following code shows how the program draws its ellipse.

// 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);

About List