Home

Windows Controls: The Numeric Up Down Control

 

Introduction to the Numeric Up Down Control

 

Description

A spin button, also called a spin box, also called an up/down control, is a Windows control equipped with two opposite arrow buttons The UpDown Control. The user clicks one of the arrow buttons at one time to increase or decrease the current value of the control. The value held by the control is also called its position.

The values of an up/down control range from a minimum to a maximum. When the up arrow button is clicked, the value of the control increases. If the user clicks and holds the mouse on the up pointing arrow button, the value of the control keeps increasing until it reaches its maximum and then stops. The opposite behavior applies when the user clicks or holds the mouse on the down-pointing arrow button.

ApplicationPractical Learning: Introducing Spin Controls

  1. Start Microsoft Visual Studion
  2. To create a new application, on the main menu, click File -> New Project
  3. In the New Project dialog box, click Windows Forms Application
  4. Set the Name to PledgeDistribution1
  5. Click OK

Creating an Up-Down Control

The .NET Framework provides two types of spin buttons. The immediate parent of the up/down control is the UpDownBase class.  This class provides the characteristics and behaviors common to both types of up/down controls.

As it name implies, the numeric up-down control is made to display numeric values. To use it, from the Common Controls section of the Toolbox, you can click the NumericUpDown button NumericUpDown and click the form or the container that will host it. This control is based on the NumericUpDown class that you can use to dynamically create the control. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : Form
{
private:
    NumericUpDown ^ nudCounter;

public:
    CExercise()
    {
        InitializeComponent();
    }
	
private:
    void InitializeComponent()
    {
        nudCounter = gcnew NumericUpDown;
        nudCounter->Location = Point(12, 12);

        Controls->Add(nudCounter);
    }
};

[STAThread]
int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    return 0;
}

This would produce:

Numeric Up-Down
 

ApplicationPractical Learning: Introducing the Numeric Up/Down Control

  1. Design the form as follows:
     
    Pledge Distribution
    Control Text Name Additional Properties
    Form   Pledge Distribution   Maximize Box: False
    Label Label Amount Pledged:    
    TextBox TextBox 0.00 txtAmountPledged Text Align: Right
    Label Label Rotherham College:    
    NumericUpDown NumericUpDown      
    Label Label %    
    TextBox TextBox 0.00 txtAmount1 Text Align: Right
    Label Label Leicester University:    
    NumericUpDown NumericUpDown      
    Label Label %    
    TextBox TextBox 0.00 txtAmount2 Text Align: Right
    Label Label Lars Union Academy:    
    NumericUpDown NumericUpDown      
    Label Label %    
    TextBox TextBox 0.00 txtAmount3 Text Align: Right
    Label Label Message lblMessage  
    Button Button Close btnClose  
  2. Execute the application to test the form
  3. Close the form and return to your programming environment
 
 
 

Characteristics of the Numeric Up-Down Control

 

The Up-Down Alignment

In traditional Win32 programming, the spin button does not have a means of displaying its value. This means that you usually have to accompany it with another control such as a text box. You also have to decide whether to place the text box to the left or the right side of the spin button control. Although the .NET Framework's up-down controls don't have this limitation, you still have to decide whether to position the arrow buttons on the left or the right side of the text box part. This property is controlled by the UpDownAlign Boolean property whose default value is Right, which places the arrow buttons on the right side. If you want the buttons to be positioned on the left, set this property to Left. The values of this property are managed through the LeftRightAlignment enumeration of the UpDownBase parent class. Here is an example of aligning the buttons to the left:

void InitializeComponent()
{
    nudCounter = gcnew NumericUpDown;
    nudCounter->Location = Point(12, 12);
    nudCounter->UpDownAlign = LeftRightAlignment::Left;

    Controls->Add(nudCounter);
}

This would produce:

The UpDown control with the buttons aligned to the left of the text box

Intercepting the Arrow Keys

When a spin button control comes up, to use it, the user can click one of the up or down-pointing buttons, which causes the value to change. The user can also press the up or down arrow keys to change the value. The ability to use the keyboard is controlled by the InterceptArrowKeys Boolean property, whose default value is True, which means the user is allowed to use the keyboard to change the value of the control. If for some (strange) reason you want to prevent the user from changing the value using the keyboard, set this property to False. If this property is set to True, remember that the user can use the keyboard only after giving focus to the control, which is usually done by pressing Tab a few times until the control receives focus. Another way the user can change the value of the control is to manually edit the value of the text box part of the control.

When the value of an spin button has been changed, the control fires a ValueChanged() event. This event simply uses an EventArgs class as argument. If the user decides to manually edit the value of the control by typing a number in the text box part of the control, the spin button fires a TextChanged() event.

The Minimum and the Maximum Values

After adding the up-down control to a container such as a form, you change its characteristics using the Properties window. Probably the most important piece of information you would need from a spin button is the value it is holding at a particular time. As mentioned already, the spin button navigates from a minimum to a maximum value. The values of the control can be natural or decimal numbers. They are actually defined as System.Decimal types. These numbers range from a minimum controlled by the Minimum property to a maximum value controlled by the Maximum property. By default, a freshly added numeric up-down control on a form has its Minimum value set to 0 and its Maximum value set to 100. You can change the values at design time in the Properties window or programmatically as follows:

void InitializeComponent()
{
    nudCounter = gcnew NumericUpDown;
    nudCounter->Location = Point(12, 12);
    nudCounter->Minimum = static_cast<Decimal>(42.58);
    nudCounter->Maximum = static_cast<Decimal>(3822046.62);

    Controls->Add(nudCounter);
}

If you use large numbers in the thousands, they may become difficult to read:

The Value of the Control

When, or while, a spin button is being used, its text box displays a value: this is the Value property. You can use this property to specify what value the control would use at startup. It can be an integer or a decimal number but it must be between the Minimum and the Maximum values. 

The Type of Value

By default, the numeric up-down displays natural numbers. Alternatively, you can make the spin button display hexadecimal numbers. The type of numbers displayed is controlled by the Boolean Hexadecimal property whose default value is False, which means that it is primarily meant to display natural numbers. If you prefer the control to display hexadecimal numbers, set this property to True. Here is an example:

void InitializeComponent()
{
    nudCounter = gcnew NumericUpDown;
    nudCounter->Location = Point(12, 12);
    nudCounter->Minimum = static_cast<Decimal>(42.58);
    nudCounter->Maximum = static_cast<Decimal>(3822046.62);
    nudCounter->Hexadecimal = true;

    Controls->Add(nudCounter);
}

This would produce:

Displaying Decimal Numbers

By default, the numeric up-down control is made to display only natural numbers. If you want it to display decimal numbers, use the DecimalPlaces property to specify the number of decimal places on the right side of the decimal separator which, in US English, is the period.

The Thousand Separator

If you want to make the control's numeric values easier to read, you can display a symbol to separate the thousands. This characteristic can be set using the Boolean ThousandsSeparator property whose default value is False. If you want to display a symbol between thousands, set this property to True. Here is an example:

void InitializeComponent()
{
    nudCounter = gcnew NumericUpDown;
    nudCounter->Location = Point(12, 12);
    nudCounter->Minimum = static_cast<Decimal>(42.58);
    nudCounter->Maximum = static_cast<Decimal>(3822046.62);
    nudCounter->ThousandsSeparator = true;

    Controls->Add(nudCounter);
}

This causes the control to check the value used as the thousands separator in the Control Panel of the computer that is using the application. The thousands separator for US English is the comma ",". Here is an example:

The NumericUpDown control displaying the thousands separator

The Incrementing Value

When using the spin button, the user clicks one of the arrows of the control to increase or decrease the value. By default, the value increases or decreases by 1. If you want the value to augment by more than 1, set the desired value using the Increment property. The value of this property can be a natural or a decimal value (it is defined as System.Decimal). To set the Increment value programmatically, you can use code as follows:

void InitializeComponent()
{
    nudCounter = gcnew NumericUpDown;
    nudCounter->Location = Point(12, 12);
    nudCounter->Minimum = static_cast<Decimal>(42.58);
    nudCounter->Maximum = static_cast<Decimal>(3822046.62);
    nudCounter->Increment = 125;
    nudCounter->ThousandsSeparator = true;

    Controls->Add(nudCounter);
}

ApplicationPractical Learning: Configuring a Numeric Up-Down Control

  1. On the form, click the top numeric up-down control
  2. In the Properties, click Value, type 50 and press Enter
  3. In the same way, change the following properties for the controls:
     
    Pledge Distribution
    Control Name Additional Properties
    NumericUpDown updAmount1 Value: 50
    NumericUpDown updAmount2 Value: 25
    NumericUpDown updAmount3 Value: 25
  4. Double-click the top up-down control and implement its event as follows:
    System::Void updAmount1_ValueChanged(System::Object^  sender, System::EventArgs^  e)
    {
        double AmountPledged = 0.00;
        double RateAmount1, RateAmount2, RateAmount3,
               Amount1, Amount2, Amount3, Rest;
    
        // Get the current value of the amount pledged
        try
        {
            AmountPledged = double::Parse(txtAmountPledged->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show("The amount you entered to pledge is not valid",
                        "Pledge Distribution",
                        MessageBoxButtons::OK,
                        MessageBoxIcon::Information);
        }
    
        // Get the percentage that is displaying in the UpDown controls other
        // than this one
        RateAmount2 = static_cast<double>(updAmount2->Value);
        RateAmount3 = static_cast<double>(updAmount3->Value);
        // To make sure that the total percentage applied on all three UpDown
        // controls is = 100, get the difference left from subtracting
        // the values of the other UpDown controls from 100
        // Use that difference as the Maximum value applied on the current
        // UpDown control
        updAmount1->Maximum = static_cast<Decimal>(100 - RateAmount2 - RateAmount3);
        // Now that we have an appropriate percentage value on the current
        // UpDown control, retrieve it
        RateAmount1 = static_cast<double>(updAmount1->Value);
    
        // Now we can calculate the amount to apply to each institution
        Amount1 = AmountPledged * RateAmount1 / 100;
        Amount2 = AmountPledged * RateAmount2 / 100;
        Amount3 = AmountPledged * RateAmount3 / 100;
        // We need the difference, if any, left after calculating the amount 
        // pledged to each institution
        Rest = AmountPledged - Amount1 - Amount2 - Amount3;
    
        // Display the value allocated to each institution 
        txtAmount1->Text = Amount1.ToString("C");
        txtAmount2->Text = Amount2.ToString("C");
        txtAmount3->Text = Amount3.ToString("C");
    
        // If there is still money left, let the user know
        if( Rest > 0)
            lblMessage->Text = Rest.ToString("C") + " still to be used";
        else
            lblMessage->Text = "";
    }
  5. Return to the form
  6. Double-click the middle up-down control and implement its event as follows:
    System::Void updAmount2_ValueChanged(System::Object^  sender, System::EventArgs^  e)
    {
        double AmountPledged = 0.00;
        double RateAmount1, RateAmount2, RateAmount3,
               Amount1, Amount2, Amount3, Rest;
    
        try
        {
            AmountPledged = double::Parse(txtAmountPledged->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show("The amount you entered to pledge is not valid",
                        "Pledge Distribution",
                        MessageBoxButtons::OK,
                        MessageBoxIcon::Information);
        }
    
        RateAmount1 = static_cast<double>(updAmount1->Value);
        RateAmount3 = static_cast<double>(updAmount3->Value);
        updAmount2->Maximum = static_cast<Decimal>(100 - RateAmount1 - RateAmount3);
        RateAmount2 = static_cast<double>(updAmount2->Value);
    
        Amount1 = AmountPledged * RateAmount1 / 100;
        Amount2 = AmountPledged * RateAmount2 / 100;
        Amount3 = AmountPledged * RateAmount3 / 100;
        Rest = AmountPledged - Amount1 - Amount2 - Amount3;
    
        txtAmount1->Text = Amount1.ToString("C");
        txtAmount2->Text = Amount2.ToString("C");
        txtAmount3->Text = Amount3.ToString("C");
    
        if( Rest > 0)
            lblMessage->Text = Rest.ToString("C") + " still to be used";
        else
            lblMessage->Text = "";
    }
  7. Return to the form
  8. Double-click the bottom up-down control and implement its event as follows:
    System::Void updAmount3_ValueChanged(System::Object^  sender, System::EventArgs^  e)
    {
        double AmountPledged = 0.00;
        double RateAmount1, RateAmount2, RateAmount3,
               Amount1, Amount2, Amount3, Rest;
    
        try
        {
            AmountPledged = double::Parse(txtAmountPledged->Text);
        }
        catch(FormatException ^)
        {
            MessageBox::Show("The amount you entered to pledge is not valid",
                        "Pledge Distribution",
                        MessageBoxButtons::OK,
                        MessageBoxIcon::Information);
        }
    
        RateAmount1 = static_cast<double>(updAmount1->Value);
        RateAmount2 = static_cast<double>(updAmount2->Value);
        updAmount3->Maximum = static_cast<Decimal>(100 - RateAmount1 - RateAmount2);
        RateAmount3 = static_cast<double>(updAmount3->Value);
    
        Amount1 = AmountPledged * RateAmount1 / 100;
        Amount2 = AmountPledged * RateAmount2 / 100;
        Amount3 = AmountPledged * RateAmount3 / 100;
        Rest = AmountPledged - Amount1 - Amount2 - Amount3;
    
        txtAmount1->Text = Amount1.ToString("C");
        txtAmount2->Text = Amount2.ToString("C");
        txtAmount3->Text = Amount3.ToString("C");
    
        if( Rest > 0)
            lblMessage->Text = Rest.ToString("C") + " still to be used";
        else
            lblMessage->Text = "";
    }
  9. Return to the form and click (once) the Amount Pledged text box
  10. In the Properties window, click the Events button
  11. Double-click the Leave field to generate its event and implement it as follows:
    System::Void txtAmountPledged_Leave(System::Object^  sender, System::EventArgs^  e)
    {
    	// Make sure the amount pledged text box has a number
        // If it doesn't, then display the UpDown controls 
        // so the user cannot use them and cause bad events
        if( txtAmountPledged->Text == "" )
        {
            updAmount1->Enabled = false;
            updAmount2->Enabled = false;
            updAmount3->Enabled = false;
        }
        else
        {
            updAmount1->Enabled = true;
            updAmount2->Enabled = true;
            updAmount3->Enabled = true;
        }
    }
  12. Return to the form 
  13. Double-click the Close button and implement its Click event its event as follows:
    System::Void btnClose_Click(Object ^ sender, System.EventArgs ^ e)
    {
        Close();
    }
  14. Test the application
     
    Test of the Pledge Distribution Application
  15. Close the form and return to your programming environment
 
 
   
 

Home Copyright © 2011 FunctionX, Inc. Home