Interacting With The User VB Net
Interacting With The User VB Net
Part of the Windows philosophy is that applications should be user-friendly. With this in mind, its
designers have provided menus, icons, Buttons, scroll bars and other tools to simplify the interaction with
the user.
Sometimes keyboard entry – the only form of input available in traditional programming languages – is
the most appropriate way to get data from the user. At other times you can make life easier for the users,
and reduce the need for error checking in your program, by asking them to select from a list, check an
option, slide a scroll bar or click on a Button.
Explore the alternatives, and whenever you want input, consider which method will be simplest for the
user.
ScrollBars
ScrollBars are familiar to any Windows user and offer a convenient way of controlling a value that can
vary between fixed limits. ScrollBars are interesting alternative to keyboard input in many situations.
Min the value when the slider is at the top, or left, of the bar.
Max the value when the slider is at the bottom, or right, of the bar.
All values must be within the normal integer range, ie. 0 to 32,767, though in practice your Max is likely
to be much tighter than that.
The next example uses ScrollBars to move a block around the screen – and the whole program contains
only three lines of code! To try it place three objects on a new form.
Panel, of a size that will fit within the limits of the scroll bars.
1
Design the following form:
VScrollBar1
picBlock
Panel
HScrollBar1 btnQuit
The purpose of the Panel is to provide a running area for the Block. Any Object placed within a Panel
cannot be moved out of it, and its Top and Left co-ordinates will be relative to the Panel, not to the Form
beneath.
As the Panel’s size is the same as the ScrollBars’ Max values, we have a simple translation of ScrollBar
values to Block co-ordinates. The Panel should be aligned as closely as possible with the ends of the
ScrollBars, inside the Arrow Buttons. The Max value of the VScrollBar control should be the same as the
Height of the Frame, and the Max of the HScrollBar the same as the Panel’s Width.
Therefore, to set the Maximum property of both the HScrollBar1 and VScrollBar1 first look at the size
property of the Panel (ie. 644,344) and use them to set Maximum property of both the HScrollBar1 and
VScrollBar1 respectively.
The Block merely needs to be visible on screen, and that can be achieved by setting the BackColor property
to a distinctive colour. Make sure that you place it within the Panel when you first define it.
2
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
End
End Sub
GroupBoxes
A Groupbox by itself does very little. The chief purpose of this control is to enclose other objects,
provididing a sort of form within a form. Probably their most common use is to hold sets of RadioButtons
or CheckBoxes, as will see below. Another sensible use for them is to enclose Labels and TextBoxes where
the Label serves as a prompt for input into the TextBox.
When a GroupBox is made visible or invisible, all the objects within it appear or disappear, when it is
moved, they all move with it. The latter is very useful at design time, and possibly during the execution of
a program.
RadioButtons
The RadioButtons controls are almost always used in sets, and only one can be selected at any one time.
This means you cannot have more than one set of options on one form – you may have placed them as
separate sets, but the system will treat them as one. The solution is to place your RadioButtons within
GroupBoxes, as each grouped set is treated separately. These provide a nice visual touch to the display as
well as being essential to the grouping of RadioButtons.
There are essentially two ways of finding out which RadioButton has been selected.
The first is to use the RadioButton’s Checked property. If the RadioButton has been selected, it will be
True. You can therefore use expressions such as:
And the statement that follow this test will only be executed if RadioButton2 has been selected. This is
probably the best approach where there are only two possible choices, as it leads to a neat
If …….. Then …….. Else ………….. structure.
The alternative is to set variable when the RadioButton is clicked. This is more suitable where there are
number of possible options, and is the approach that has been used in the following example. It deals,
appropriately enough, with options, though the options in this case are subject choices.
A student must choose one language, from Option Block 1, and one creative subject, from Option Block
2. Each block is represented by a Groupbox on the form, and the RadioButtons should be suitably named.
The variable Choice1 and Choice2 are used to collect the choices, and are declared at the top of the form
so that they are available to every sub. Values are assigned to these variables when the RadioButtons are
clicked. When the Show Choice Button is clicked, their current values should be displayed in the TextBox.
3
Form design with the sample output:
GroupBox RadioButton
btnQuit
lblChoices
btnShow
4
End Sub
The defaults are French and Art. These are set at design time, by selecting True for their Checked property.
If the Checked was to be used directly in the program, no further action would be needed. As we handling
the selection through variables, we must also set default values for them. This can be done in the
Form_Load sub – double-click anywhere on the form to get into this sub.
CheckBoxes
The key difference between RadioButtons and CheckBoxes, apart from the shape of their symbols, is that
any number of CheckBoxes in a set may be True at once. As with RadioButtons, you can test the Checked
property of a CheckBox directly. In the statement:
the actions following Then would be executed if Checked was True. And you must test the value of
Checked, even in a CheckBox’s CheckChanged sub, for clicking will turn the box On and Off, toggling
between the two states. This is different from a RadioButton, where a click always turns it on.
In the Xmas list example shown below, the user is offered a choice of presents and asked to check those
that he or she would like.
The variable gifts is used as a counter, and increased by 1 each time a CheckBox is turned on. When the
Done Button is pressed, the code will display a different message, depending upon the greed of the user.
The Checked property of the CheckBox is changed as soon as it is clicked, and before the system gets to
the CheckChanged sub. Knowing this, we can write code for those subs that will add to the gifts count if
the box is checked and subtract if the click has turned it off.
5
Design the following form:
chkPhone
chkLaptop
Groupbox
chkFerrari
chkRolex
chkTeddy
btnDone btnQuit
6
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
End
End Sub
In this simple example, the code on the Done Button concentrates on the gifts total and largely ignores
the states of the individual Checkboxes. (Note the special message that is given to those who only want a
teddy!) In practice, any program which used CheckBoxes would also want to react to their specific values.
Menus
Look at any Windows application and you will see that it has a menu system. Because it is the simplest
and clearest way of showing your users the full range of facilities in your program, and of giving access to
those facilities. Creating a menu is straightforward.
7
To add a menu bar to an application, drop a MenuStrip control onto the form – don’t bother about trying
to locate it carefully as it knows where to go. There are two visible results: Menu bar at the top and
Component tray appears at the bottom of the workspace, with the MenuStrip component placed on it.
At the top of the form on the menu bar, Click on the grey “Type Here” message and type menu item such
as Controls, as soon as you click on the grey “Type Here” down below the menu you typed appears another
textbox with the word in grey “Type Here” for filling options.
Here we’ll construct menu system that has Controls menu with options such as New Problem, Check
Answer, Type of Sum and Exit menu with options such as Yes and No and perhaps others. As shown in
the figure below:
When typing the menu entries, one of the letters – usually the first – should be set so that it is underlined
and can be selected by the [Alt] + key combination. To do this, type an ampersand (&) before it. When
you move on to the next item, the & will disappear and the letter will be underlined. Watch out for
duplication! You cannot use the same selecting letter twice in the same menu.
To start a new main menu: type the heading in the menu bar.
A new “Type Here” will appear beside it (for the next main heading) and below it (for a menu item)
8
To add an item to a menu: type below the existing items.
To start a new submenu: select the entry that leads to the submenu then type the first item in
the “Type Here” to its right.
To insert a separator line: right-click on the item below where the separator is to go, then select
Insert and then select Separator from the pop-up menu.
To edit a menu entry: click on it once to select it, then again to place the typing cursor into it and
edit as normal.
To move a menu entry: click on it and drag it to its new position.
To stop work on the menus: click anywhere else on the form.
To restart work on the menus: click on any heading in the menu bar.
Setting properties
At this stage you have the shape of the menus and the text for the entries, but little else. Each item has
been allocated a name such as ToolStripMenuItem1, ToolStripMenuItem2, etc., and these should be
renamed to identify them clearly. To rename a menu item:
While you are at the Properties window, you can also set the options. There is a key one to note which is:
Checked that puts a tick by the entry, to show that an on/off option is on.
This option should be set to True at design time, if the default settings is on. Otherwise it can be set during
run-time.
Adding code
When the user select the menu item, whether by clicking or using an [Alt] + key combination, it triggers a
Click event. The menu command’s code could be written directly there, but if you want to be able to
activate the same command from a toolbar Button – as we’ll do here – it is better to write the code in a
separate subroutine.
Context menus
The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when you
right click them. They appear in context of some specific controls, so are called context menus. For
example, Cut, Copy or Paste options.
This control associates the context menu with other menu items by setting that menu item's
ContextMenuStrip property to the ContextMenuStrip control you designed.
9
Context menu items can also be disabled, hidden or deleted. You can also show a context menu with the
help of the Show method of the ContextMenuStrip control.
A context menu is built in almost the same way as a main menu. The main differences are that the context
menu must be linked to an object and there can only be one main list of options. To create a context
menu:
Example
In this example, let us add a content menu with the menu items Cut, Copy and Paste.
Take the following steps −
Drag and drop or double click on a ControlMenuStrip control to add it to the form.
10
Add the menu items, Cut, Copy and Paste to it.
Add a RichTextBox control on the form.
Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the
properties window.
Double the menu items and add following codes in the Click event of these menus:
Now, you can select any menu items and perform cut, copy or paste on the text box.
Toolbars
Toolbars are unexpectedly different from menus in the way that they are created and used. This probably
because a toolbar is a simple item, and its Buttons are segments within it – while on a menu, each entry
is a separate item, and the structure is a container to hold them. You can see this when you set up the
11
toolbar. To add code to the toolbar button just double-click the particular button and it will take you
straight to that button’s subroutine.
It shows up again in the way that toolbar icons are managed. Tools have their own image property. To
add image icon to the toolbar’s button, first select that button and click “image” property in the properties
window and select the file path in the dialogbox that appears. You can build a text-only toolbar and add
the images later. We’ll start with text, so that we can get our heads around toolbars before we worry
about making them pretty.
To create a toolbar:
1. Select the Toolbar control from the Toolbox and drop it onto the form. It will automatically locate
itself just below the menu bar.
2. Click drop drown arrow on the icon that appears on the toolbar control and Select Button option
and the button will appear on the toolbar.
3. Select the added button and go to properties windows and edit the Text property and type the
text to be displayed on the Button (type New). Also edit the DisplayStyle property and choose
Text. And also set ToolTip Text property, if required.
4. Repeat steps 2 and 3 to add the other Buttons.
The default toolbar Button style is PushButton, but there are other options as shown in the figure above.
You can add Label, SplitButton, DropDownButton, ComboBox, TextBox and ProgressBar in the toolbar.
Play around with these tools to see how they appear in the toolbar.
Worked example
This is an arithmetic test program, where the type and difficulty of the problems can be set by the user.
The controls include a ScrollBar, a set of OptionButtons and a Menu, as well as others covered in earlier.
In its code you will find a Select Case and a variety of If structures. Another point to note here is how the
values held by some of the controls are treated as variables.
We’ll start with the form design and look at the actions that arise from the use of the controls.
12
Form Design
For this program we want a form that will display an arithmetic problem and accept and check an answer.
It should have a means of changing the type of sum and the level of difficulty, and should display the
score. A layout is shown below:
ToolStripButton lblNum2
lblSumtype
lblNum1
txtAnswer
grpType
rdoAdd
hsbLevel
rdoSub
rdoTimes lblScore
rdoDiv
It’s limits are the Min and Max properties which are set at design time. If the program is intended for
use by young children, the limits might be set at 5 and 10; for older users, armed with calculators,
they might be 10 to 100 or more.
13
lblScore is a Label to display the score and is updated by the checking code. The variables that count
the number of problems and of correct answers must be declared at the top of the form so that they
are generally available.
Menu commands
These replicate the effects of the controls on the form. Though this is unnecessary, you will often find
similar situations in Windows application programs. It takes very little code to offer menu, keystroke and
toolbar or Button alternatives to activate the same command, but it does give your users the choice. Some
people like to pick their way through menus, others prefer a quick click on the screen. We are using menus,
Buttons and a toolbar here to give practice in all three.
The toolbar
The example developed here has only three Buttons: New, Check and End. When clicked, these will run
the subs to generate a new problem, check the answer and exit from the program. I have left them as
text-only; you can add images if you like.
Coding
Much of the code flows naturally from the specifications of the controls, with a little more detailed design
needed for a couple of larger routines.
14
General variables and default values
You need generally accessible variables to store the correct answer (Ans), the count of right answers
(rtans) and the count of questions (qcount). These variables should be declared at the top of the code,
above the first sub.
Their initial values should be set in the Form_Load sub. The default type of sum and level of difficulty
should also be set at this point.
KeyPress Event
The answer must be checked. We are offering our user a Check Answer Button and a menu option, but
we should also run the check automatically after an [Enter] keypress that will tell us that he or she has
finished typing the answer. We are going to have to dig into the parameters to do this.
The KeyPress code has an e parameter which holds the KeyPressEventArgs. Within this is KeyChar, which
holds the character that was last pressed. In this case we are looking for [Enter] which is Chr(13). That
gives us this code:
Note that KeyPress is not the default event for a TextBox. To open this sub in the Code window, select
txtAnswer from the Class Name drop-down list, on the left above the code, and then KeyPress from the
Method Name list on the right.
lblSumType.Text = ”+”
As there is so little code, it’s not a problem to duplicate it in both the menu command and the Button.
Random numbers
The Rnd() function produces a fractional value in the range of 0 to 1. It is pseudorandom – i.e. every value
is as likely as every other, and you cannot predict what will come next, but it is actually the result of
complex calculation. Values such as 0.4162738746 are rarely much use in a program, but they can easily
be converted into more useful ones by expressions following this pattern:
num = Int (Rnd * range ) + base
The base number is necessary as Int() truncates values – it chops off the decimal part, leaving just the
integer. Consider the table below, look what happens with these values:
15
Rnd Rnd * 6 Int (Rnd * 6 ) Int (Rnd * 6) + 1
0.54 3.24 3 4
0.05 0.30 0 1
0.90 5.40 5 6
The calculation that produces random numbers always works through the same sequence, but this is so
complex that you cannot predict the next number, as long as you start at a different place each time. To
make the system select a new start point, based on the system’s clock, place the statement Randomize()
in the Form_Load code.
16
Private Sub rdoAdd_CheckedChanged(sender As Object, e As EventArgs) Handles_
rdoAdd.CheckedChanged
lblSumtype.Text = "+"
End Sub
17
Private Sub ToolStripBtnCheck_Click(sender As Object, e As EventArgs) Handles_
ToolStripBtnCheck.Click
CheckAnswer()
End Sub
18