BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
The two previous parts of this mini-blog have shown how to draw forms and how to write code to handle form events. This final part shows how to add some of the more exotic controls to user forms, like combo boxes, list boxes, multipage controls, spinners and option buttons.
- Advanced Controls - Our Example
- Multipage Controls
- Combo boxes (and list boxes)
- Multiple Column Combo Boxes and Listboxes
- Multi-select ListBoxes
- SpinButtons (Spinners) (this blog)
- Check Boxes
- Option Buttons (Radio Buttons)
- The Calendar Control
Posted by Andy Brown on 28 February 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
SpinButtons at first glance look clunky and unnecessary:
The SpinButton allows the user to change the number of sugars ordered.
However, the reason that they are so useful is that they allow you to prevent users typing in numbers directly:
The textbox for the number of sugars has the Enabled property set to False - this means that a user can't change the value directly.
If a user can't type in a number directly, you don't have to validate its data type or values. This is a big advantage!
Creating a SpinButton
To create a SpinButton, just click on the tool and then click where you want it to go:
Don't confuse the SpinButton tool with the scroll bar tool ...
A SpinButton usually sits next to the textbox whose value it will affect:
Here the SpinButton will control the value in the txtSugar textbox.
That's the easy part. When you double-click on the SpinButton to write code, you get an odd default event:
Private Sub spnSugar_Change()
It's more likely that you would attach code to the SpinDown and SpinUp events.
Writing a Generic Procedure to Handle Spinning Up and Down
It's good programming practice to write a single procedure to handle both possible spin directions. For our example, this could be:
Sub AddSugar(NumberAdd As Integer)
Dim CurrentSugars As Integer
'find out how many sugars currently
CurrentSugars = CInt(Me.txtSugar.Text)
CurrentSugars = CurrentSugars + NumberAdd
'don't allow negative sugars
txtSugar.Text = IIf(CurrentSugars > 0, CurrentSugars, 0)
Here we'll pass in the number of sugars to add (this can be negative). The routine makes sure that you don't set the number of sugars to be less than 0.
Attaching Code to the SpinButton Events
If you've written a generic procedure as above, you just need to call it twice - once when you spin up, and once when you spin down:
Private Sub spnSugar_SpinDown()
'add a sugar
Private Sub spnSugar_SpinUp()
'remove a sugar, if any left to remove
When you click on the down arrow of the SpinButton, for example, it will call the AddSugar routine to add -1 sugars.