NumericUpDown and TrackBar

Two controls take a number from the user. NumericUpDown is a text box with two arrows and a range, exact to the decimal place. TrackBar is a slider whose value the user moves with the mouse, cheap to use and hard to set exactly. A form often has both over one value, which is the exercise at the end of the lesson.

NumericUpDown

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly NumericUpDown _price = new() { Location = new Point(16, 16), Width = 140, Minimum = 0m, Maximum = 1000000m, DecimalPlaces = 2, Increment = 0.50m, ThousandsSeparator = true, Value = 1250m, }; private readonly Label _status = new() { Location = new Point(16, 56), AutoSize = true }; public Form1() { Text = "Price"; ClientSize = new Size(360, 110); _price.ValueChanged += (sender, e) => _status.Text = $"value: {_price.Value:0.00}, digits: {_price.Value.ToString().Length}"; Controls.Add(_price); Controls.Add(_status); _status.Text = $"value: {_price.Value:0.00}"; } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. Value is a decimal, which is what an amount of money needs; DecimalPlaces fixes the display and the smallest step the arrows take, while Increment is how much one press of an arrow changes. Minimum and Maximum clamp everything: a typed value below the minimum becomes the minimum when the field is left, and a programmatic assignment outside the range throws ArgumentOutOfRangeException.

The text can still be typed, and the control parses it when the field loses the focus. A text it cannot parse reverts to the previous value, and ParseEditText applies the same rule from code. ValueChanged fires for a click on an arrow, for the parsed text and for an assignment in the constructor, so a handler must be prepared to run before the form is shown.

TrackBar

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly TrackBar _volume = new() { Location = new Point(16, 16), Width = 300, Minimum = 0, Maximum = 100, TickFrequency = 10, SmallChange = 1, LargeChange = 10, Value = 40, }; private readonly Label _status = new() { Location = new Point(16, 60), AutoSize = true }; public Form1() { Text = "Volume"; ClientSize = new Size(340, 120); _volume.ValueChanged += (sender, e) => _status.Text = $"{_volume.Value} %"; Controls.Add(_volume); Controls.Add(_status); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. TickFrequency decides how many ticks are drawn, not which values are allowed: the thumb still moves through every integer between Minimum and Maximum. A slider that must land on tens has to snap by hand. LargeChange is the step of Page Up and Page Down, SmallChange the step of the arrow keys once the control has the focus.

Two events matter: ValueChanged fires every time the value changes, including a programmatic assignment, and Scroll fires while the user drags. A handler that does expensive work listens to Scroll with a guard, or does the work on a timer; the freezes lesson of the thread part explains why.

One value, two controls

A volume slider next to a number box is a common pair, and the trap is a loop: the slider changes the number, the number changes the slider, and the two handlers call each other. The usual answer is one method that writes both and a guard that stops the re-entry:

using System; using System.Drawing; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly TrackBar _slider = new() { Minimum = 0, Maximum = 100, Value = 40 }; private readonly NumericUpDown _box = new() { Minimum = 0, Maximum = 100, Value = 40 }; private bool _syncing; public Form1() { Text = "One value"; ClientSize = new Size(340, 120); _slider.Location = new Point(16, 16); _slider.Width = 200; _box.Location = new Point(232, 16); _slider.ValueChanged += OnSlider; _box.ValueChanged += OnBox; Controls.Add(_slider); Controls.Add(_box); } private void OnSlider(object? sender, EventArgs e) => Sync(_slider.Value); private void OnBox(object? sender, EventArgs e) => Sync((int)_box.Value); private void Sync(int value) { if (_syncing) { return; } _syncing = true; try { _slider.Value = value; _box.Value = value; } finally { _syncing = false; } } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. The guard is not the only way, and it is the simplest: the alternative is to subscribe only to the control the user can move and to assign the other one, which works until the value also changes from code.

The arithmetic that runs

Whatever the controls look like, the number has to be clamped to a range and often snapped to a step. That is arithmetic, and it runs here:

using System; using System.Globalization; var inputs = new[] { "-5", "0", "42.5", "100", "150" }; foreach (var text in inputs) { var value = Clamp(decimal.Parse(text, CultureInfo.InvariantCulture), 0m, 100m); Console.WriteLine($"{text,5} -> {value,6:0.0} snapped {Snap(value, 10),3}"); } Console.WriteLine($"ticks: {100 / 10 + 1}"); static decimal Clamp(decimal value, decimal min, decimal max) => Math.Min(max, Math.Max(min, value)); static int Snap(decimal value, int step) => (int)Math.Round(value / step) * step;

dotnet run

   -5 ->    0.0  snapped   0
    0 ->    0.0  snapped   0
 42.5 ->   42.5  snapped  40
  100 ->  100.0  snapped 100
  150 ->  100.0  snapped 100
ticks: 11

The output is the real run. Two rules are visible in it. The clamp is what Minimum and Maximum do to a typed value, and it is the one piece of a numeric control a program must repeat when the value arrives from a file instead of a user. The snap is what a slider needs when only multiples of ten are allowed: 42.5 becomes 40, not 45, because Math.Round without a mode rounds a halfway value to the even number, which is what the run printed.

Exercises

  1. Change the snap to round halfway values up and run the program again. Which lines change?
  2. Make a clamp with an inclusive maximum and print what happens for a maximum of 99.9 and an input of 100.
  3. Explain from the documentation what NumericUpDown does when the user types text it cannot parse and leaves the field.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What type is NumericUpDown.Value?

    Answer

    decimal

    A decimal, which is what an amount of money needs.

  2. What does DecimalPlaces control?

    Answer

    The displayed decimals and the smallest step of the arrows

    It fixes the display and the arrow step; Increment is the amount of one press.

  3. What happens to a typed value below Minimum when the field is left?

    Answer

    It is clamped to Minimum

    The range is enforced on the parsed text.

  4. What does TickFrequency decide?

    Answer

    How many ticks are drawn, not which values are allowed

    The thumb still moves through every integer unless the code snaps the value.

  5. Which event fires while the user drags the thumb?

    Answer

    Scroll

    Scroll is the drag event; ValueChanged also fires for a programmatic assignment.

  6. What does LargeChange set?

    Answer

    The step of Page Up and Page Down

    SmallChange is the arrow step and LargeChange the page step.

  7. Why does the slider and number box pair need a _syncing flag?

    Answer

    Each handler would change the other control and re-enter itself

    Writing both values from one method with a guard stops the loop.

  8. What did the run print for 42.5 snapped to a step of 10?

    Answer

    40

    Math.Round without a mode rounds 4.25 to the even number, so the step is 40.

  9. What did the run print for -5 before snapping?

    Answer

    0.0

    The clamp raised it to the minimum of 0.

  10. Why must a handler of ValueChanged be ready to run before the form is shown?

    Answer

    Assigning Value in the constructor raises it

    An assignment is a change, so a constructor handler sees a half-built form.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev