Title: Use a scrollbar to select non-integer values in C#
The Trackbar and scrollbar controls let the user select integer values, but sometimes it's useful to let the user select a non-integer value. You can let the user type into a text box but then the user can enter invalid values.
This example uses a scrollbar to let the user select non-integer values between 0 and 100 to the nearest 1/100th. The trick is to scale everything by a multiple of 100.
In this example the scrollbar's LargeChange property is 100 so clicking on the scrollbar's body changes its value by 100. When you divide by 100, that makes the selected value change by 1.00.
The largest value a user can select with a scrollbar is Maximum - LargeChange + 1. To allow the user to select values between 0 and 10,000 (which is 100 times 100) in the upper scrollbar, I set Minimum = 0, Maximum = 10099, and LargeChange = 100. Now the user can select values between 0 and 10,000.
The lower scrollbar's properties are the same except it has Minimum = 5000.
The following code shows how the program scales the user's selections when the scrollbar values change.
// Display the 1st selected value.
private void scrValue_Scroll(object sender, ScrollEventArgs e)
{
float value = scrValue1.Value / 100f;
lblValue1.Text = value.ToString("0.00");
}
// Display the 2nd selected value.
private void scrValue2_Scroll(object sender, ScrollEventArgs e)
{
float value = scrValue2.Value / 100f;
lblValue2.Text = value.ToString("0.00");
}
The code simply scales the selected values by dividing them by 100f. Note that the code divides by the floating point value 100f instead of the integer value 100. If you divide by 100, the program performs integer division so the result is always an integer instead of including two decimal places.
Note that it's not easy for the user to pick a specific value to the nearest hundredth. The user can click on the control's arrows and the area between the thumb and the arrows to select values precisely, but it's more work than picking a value in a smaller range. To make picking specific values easier, you should use a large scrollbar and allow the fewest possible choices. In this example, you could let the user pick values to the nearest 10th instead of the nearest 100th.
Download the example to experiment with it and to see additional details.
|