Home

Spin Buttons

 

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.

 

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:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private nudCounter As NumericUpDown


        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            Controls.Add(nudCounter)

        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

This would produce:

Numeric Up-Down
 

Practical LearningPractical Learning: Introducing the Numeric Up/Down Control

  1. Start Microsoft Visual Basic
  2. Create a new Windows Application named PledgeDistribution1
  3. In the Solution Explorer, right-click Form1.vb and click Rename 
  4. Type PledgeDistribution.vb and press Enter
  5. Design the form as follows:
     
    Pledge Distribution
    Control Text Name Additional Properties
    Form Pledge Distribution   Maximize Box: False
    Label Amount Pledged:    
    TextBox 0.00 txtAmountPledged Text Align: Right
    Label Rotherham College:    
    NumericUpDown      
    Label %    
    TextBox 0.00 txtAmount1 Text Align: Right
    Label Leicester University:    
    NumericUpDown      
    Label %    
    TextBox 0.00 txtAmount2 Text Align: Right
    Label Lars Union Academy:    
    NumericUpDown      
    Label %    
    TextBox 0.00 txtAmount3 Text Align: Right
    Label Message lblMessage  
    Button Close btnClose  
  6. Execute the application to test the form
  7. 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:

Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            nudCounter.UpDownAlign = LeftRightAlignment.Left

            Controls.Add(nudCounter)

End Sub

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:

Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            nudCounter.Minimum = 42.48D
            nudCounter.Maximum = 3822046.06D

            Controls.Add(nudCounter)

End Sub

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:

Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            nudCounter.Minimum = 42.48D
            nudCounter.Maximum = 3822046.06D

            nudCounter.Hexadecimal = True

            Controls.Add(nudCounter)

End Sub

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:

Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            nudCounter.Minimum = 42.48D
            nudCounter.Maximum = 3822046.06D

            nudCounter.ThousandsSeparator = True

            Controls.Add(nudCounter)

End Sub

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:

Public Sub InitializeComponent()

            nudCounter = New NumericUpDown()
            nudCounter.Location = New Point(12, 12)

            nudCounter.Minimum = 42.48D
            nudCounter.Maximum = 3822046.06D

            nudCounter.Increment = 125.82D

            nudCounter.ThousandsSeparator = True

            Controls.Add(nudCounter)

End Sub

Practical LearningPractical 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:
     
    Private Sub updAmount1_ValueChanged(ByVal sender As System.Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles updAmount1.ValueChanged
            Dim AmountPledged As Double
            Dim RateAmount1 As Double
            Dim RateAmount2 As Double
            Dim RateAmount3 As Double
            Dim Amount1 As Double
            Dim Amount2 As Double
            Dim Amount3 As Double
            Dim Rest As Double
    
            ' Get the current value of the amount pledged
            Try
                AmountPledged = CDbl(txtAmountPledged.Text)
            Catch ex As FormatException
                MsgBox("The amount you entered to pledge is not valid")
            End Try
    
            ' Get the percentage that is displaying in the UpDown controls other
            ' than this one
            RateAmount2 = CType(updAmount2.Value, Double)
            RateAmount3 = CType(updAmount3.Value, Double)
            ' 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 = CType(100 - RateAmount2 - RateAmount3, Double)
            ' Now that we have an appropriate percentage value on the current
            ' UpDown control, retrieve it
            RateAmount1 = CType(updAmount1.Value, Double)
    
            ' 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 = FormatCurrency(Amount1)
            txtAmount2.Text = FormatCurrency(Amount2)
            txtAmount3.Text = FormatCurrency(Amount3)
    
            ' If there is still money left, let the user know
            If Rest > 0 Then
                lblMessage.Text = Rest.ToString("C") & " still to be used"
            Else
                lblMessage.Text = ""
            End If
    End Sub
  5. In the Class Name combo box, select updAmount2
  6. In the Method Name combo box, select ValueChanged and implement the event as follows:
     
    Private Sub updAmount2_ValueChanged(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles updAmount2.ValueChanged
            Dim AmountPledged As Double
            Dim RateAmount1 As Double
            Dim RateAmount2 As Double
            Dim RateAmount3 As Double
            Dim Amount1 As Double
            Dim Amount2 As Double
            Dim Amount3 As Double
            Dim Rest As Double
    
            Try
                AmountPledged = CDbl(txtAmountPledged.Text)
            Catch ex As FormatException
                MsgBox("The amount you entered to pledge is not valid")
            End Try
    
            RateAmount1 = CType(updAmount1.Value, Double)
            RateAmount3 = CType(updAmount3.Value, Double)
            updAmount2.Maximum = CType(100 - RateAmount1 - RateAmount3, double)
            RateAmount2 = CType(updAmount2.Value, Double)
    
            Amount1 = AmountPledged * RateAmount1 / 100
            Amount2 = AmountPledged * RateAmount2 / 100
            Amount3 = AmountPledged * RateAmount3 / 100
            Rest = AmountPledged - Amount1 - Amount2 - Amount3
    
            txtAmount1.Text = FormatCurrency(Amount1)
            txtAmount2.Text = FormatCurrency(Amount2)
            txtAmount3.Text = FormatCurrency(Amount3)
    
            If Rest > 0 Then
                lblMessage.Text = Rest.ToString("C") & " still to be used"
            Else
                lblMessage.Text = ""
            End If
    End Sub
  7. In the Class Name combo box, select updAmount3
  8. In the Method Name combo box, select ValueChanged and implement the event as follows:
     
    Private Sub updAmount3_ValueChanged(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles updAmount3.ValueChanged
            Dim AmountPledged As Double
            Dim RateAmount1 As Double
            Dim RateAmount2 As Double
            Dim RateAmount3 As Double
            Dim Amount1 As Double
            Dim Amount2 As Double
            Dim Amount3 As Double
            Dim Rest As Double
    
            Try
                AmountPledged = CDbl(txtAmountPledged.Text)
            Catch ex As FormatException
                MsgBox("The amount you entered to pledge is not valid")
            End Try
    
            RateAmount1 = CType(updAmount1.Value, Double)
            RateAmount2 = CType(updAmount2.Value, Double)
            updAmount3.Maximum = CType(100 - RateAmount1 - RateAmount2, Double)
            RateAmount3 = CType(updAmount3.Value, Double)
    
            Amount1 = AmountPledged * RateAmount1 / 100
            Amount2 = AmountPledged * RateAmount2 / 100
            Amount3 = AmountPledged * RateAmount3 / 100
            Rest = AmountPledged - Amount1 - Amount2 - Amount3
    
            txtAmount1.Text = FormatCurrency(Amount1)
            txtAmount2.Text = FormatCurrency(Amount2)
            txtAmount3.Text = FormatCurrency(Amount3)
    
            If Rest > 0 Then
                lblMessage.Text = Rest.ToString("C") & " still to be used"
            Else
                lblMessage.Text = ""
            End If
    End Sub
  9. In the Class Name combo box, select txtAmountPledged
  10. In the Method Name combo box, select Leave and implement the event as follows:
     
    Private Sub txtAmountPledged_Leave(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles txtAmountPledged.Leave
            ' 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 = "" Then
                updAmount1.Enabled = False
                updAmount2.Enabled = False
                updAmount3.Enabled = False
            Else
                updAmount1.Enabled = True
                updAmount2.Enabled = True
                updAmount3.Enabled = True
            End If
    End Sub
  11. In the Class Name combo box, select btnClose
  12. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  13. Test the application
     
    Test of the Pledge Distribution Application
  14. Close the form and return to your programming environment

Introduction to the Domain Up Down Control

 

Description

A spin button, also called an up-down control, is usually made to display a numeric value that can then be increased or decreased when the user clicks one of the buttons of the controls. In a Microsoft Windows typical application, if you wanted to deal with values other than numbers, there was some gymnastic code to write. Fortunately, the .NET Framework provides a special spin button that can hold and display values other numbers.

The .NET Framework's domain up-down control is a text-based object created from a class named DomainUpDown. Like NumericUpDown, the DomainUpDown class is derived from the UpDownBase class where it gets its primary functionality from.

Creating a Domain Up-Down Control

At design time, to get a domain up-down control, from the Toolbox, you can click the DomainUpDown button and click the form. To programmatically create a domain up-down control, declare a variable of type DomainUpDown, initialize it and add it to the Controls property of the container that will hold it. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private spnNames As DomainUpDown

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()

            spnNames = New DomainUpDown()

            Controls.Add(spnNames)

        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

This would produce:

Characteristics of the Domain Up-Down Control

 

Introduction

The spin button shares the normal characteristics of other graphical Windows controls that they inherit from their ancestor the Control class. These characteristics including the location, the size, the background color, the ability to be enabled or disabled, the ability to be hidden or shown, etc. As a text-based object, the domain up-down control uses characteristics such as the ability to display text, alignment of text, and the ability to resize itself according to the length of its text, which is based on the AutoSize property.

Because the DomainUpDown class is derived from the UpDownBase class, it inherits the ability to specify on what side of the text box the spin button will align, to the left or to the right. This is controlled by the UpDownAlign property. The DomainUpDown class also inherits the ability to let the user manually change the value of the control. This is supported by the UserEdit Boolean property.

The Text of the Control

When using the spin button, the user can click one of the arrow buttons. This would bring the next or the previous string of the list and display that item in the text box part of the control. The user can also first give focus to the control, and then use the arrow keys to navigate in the list of strings.

At any time, the string that is currently displaying on the spin button is represented by its Text property. To specify the string that the control should display, at design time, you can enter the string in the Text field of the Properties window. To programmatically specify what item the control should display, assign it to its Text property. Here is an example:

Public Sub InitializeComponent()

            spnNames = New DomainUpDown()
            spnNames.Location = New Point(12, 12)

            spnNames.Text = "Paul Yamaguchi"

            Controls.Add(spnNames)

End Sub

This would produce:

You can even use a string that is not in the collection. If you do, the control would display it but if the user changes the current item of the control that string would disappear and the user cannot get it back.

The Items of the Control

As mentioned already, instead of displaying (only) numbers, the domain up-down control can be used to display strings (and/or numbers). To make this possible, the control must hold a list the strings to display. This list is held by the Items property. At design time, to create a list of values, in the Properties window of the control, click Items and click its ellipsis button. This would open the String Collection Editor

String Collection Editor

You can then type each string on its own line (of course, you can type only numbers or a mix of numbers and strings). After creating the list, you can click OK.

The DomainUpDown.Items property is based on the nested DomainUpDownItemCollection class. The DomainUpDownItemCollection class is derived from the ArrayList class which gives it the ability to create and manage its list. To programmatically add a string to the list, call its Add() method. You can do this continually until you have added all the necessary strings. Here is an example:

Public Sub InitializeComponent()

            spnNames = New DomainUpDown()
            spnNames.Location = New Point(12, 12)

            spnNames.Items.Add("Patricia Katts")
            spnNames.Items.Add("Paul Bertrand Yamaguchi")
            spnNames.Items.Add("Marguerite Soya")

            Controls.Add(spnNames)

End Sub

Instead of adding one item at a time, the DomainUpDownItemCollection class is equipped with a method named AddRange. This allows you to add an array of items. Here is an example:

Public Sub InitializeComponent()

            spnNames = New DomainUpDown()
            spnNames.Location = New Point(12, 12)

            spnNames.Items.Add("Patricia Katts")
            spnNames.Items.Add("Paul Bertrand Yamaguchi")
            spnNames.Items.Add("Marguerite Soya")

            Dim Names() As String = _
            { _
                "Huguette Lingon", "Peter Kabba", _
                "Harry Almada", "Allen Dean" _
            }
            spnNames.Items.AddRange(Names)

            Controls.Add(spnNames)

End Sub

When calling Add() (or AddRange()), the new item(s) is(are) added at the end of the existing list, unless the list is empty, in which case the item(s) would be the first. The DomainUpDownItemCollection class is also equipped with a method named Insert() that allows you to add a new item somewhere inside the list at a position of your choice.

Sorting the List

As you create the list of strings, they are added either at the end (with Add() or AddRange()) or inserted (with Insert()) at the position of your choice. If you want the items to be arranged in alphabetical or chronological order, use the Sorted Boolean property.

To find out whether the list is sorted or not, get the value of the control's Sorted property.

The Index of the Current String

When the user clicks one of the buttons of the spin control or use an arrow key to change the item, the control fires a SelectedItemChanged event. You can use this event to find out what the index of the item that was selected. You have to alternatives.

You can identify an item by its index. The index of the current item is represented by the SelectedIndex property, which is an integer. If you prefer to locate an item by its name (or string), you can use the SelectedItem property, which is of type object. You can also use the SelectedItem property to specify the string that the spin button should display. To do this, simply assign a string to this property. Here is an example:

Public Sub InitializeComponent()

            spnNames = New DomainUpDown()
            spnNames.Location = New Point(12, 12)

            spnNames.Items.Add("Patricia Katts")
            spnNames.Items.Add("Paul Bertrand Yamaguchi")
            spnNames.Items.Add("Marguerite Soya")

            Dim Names() As String = _
            { _
                "Huguette Lingon", "Peter Kabba", _
                "Harry Almada", "Allen Dean" _
            }
            spnNames.Items.AddRange(Names)

            spnNames.SelectedItem = "Peter Kabba"

            Controls.Add(spnNames)

End Sub

Unlike the Text property, if you assign a string that is not in the list, it would not show in the text box part of the control. This means that, if you assign a string (that is not in the list of control's strings) to the Text property, the compiler would simply display that string in the control. On the other hand, when you assign a string to the SelectedItem property, the compiler would check in the list if that string exists. If it finds it, then it displays it in the text box. If it does not find, it does nothing: it does not throw an exception.

Wrapping the List Navigation

As mentioned previously, when the user navigates through the list, the items are changed one after another. When the user gets to the end of the list, the navigation stops and the user cannot go further. As an alternative, when the user gets to the end of the list and click the up button, if you want, you can make the list restart from the beginning. This characteristics is controlled by the Wrap Boolean property whose default value is false.

To find out whether the control is currently set to wrap, get the value of its Wrap property.

 

 

Previous Copyright 2008-2009, yevol.com Next