Programming for Computing 07 - 08

Chapter: Controls and events

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

Why do we do this...

 


Section 14.0

In the 'old days' there was a Dos-style screen, which allowed the displaying and inputting of lines of text. In modern-day windows programming however, there is a wide range of I/O controls (widgets, components, gizmos). For the purposes of learning to program, we will initially use only a few of these - label, button, text box , radio button - but information on other controls is also provided.

What is the difference between a variable (which you know about) and a control?

A variable - holds a single value at once - such as an integer - and it is held in RAM (not automatically displayed on the screen).

A control holds a set of values, and is - usually - displayed on the screen. Imagine a filing cabinet, named money. (We may have several cabinets, so each one has a name). It has several drawers, which might be labelled: bills, debts, statements.

If we want to refer to the bills drawer in the money cabinet, the VB approach is:


    money.bills

This 'dot' notation is common in most programming languages. Now consider the Button in VB. it has an on-screen representation (a grey rectangle) and it contains several items, such as:

its text - the text the user sees (a string)
its height - an integer
its position: two items named left and top (both integers) giving the x/y position of the top-left corner of the button.

Items such as left, right, text, are termed PROPERTIES

Controls need a name - because we might have several, and need to distinguish between them

When we put a button on a form, VB gives it an initial name of Button1. The next button will be named Button2 etc... We can reset these names to a more meaningful name if we wish (see later), at design-time.

In general to use a property, we put:

    ControlName.property

Controls also have events, in which a procedure (a private sub) is called up when the user manipulates a control. Note that controls can trigger several events. For example, a button can tell you when the mouse enters the area of a button, or when the mouse is hovering over a button, or when the mouse leaves the area of the button. But normally, we only pick pu the 'click' event. You detect the occurrence of these events by selecting them at the top-right of the code window. VB creates a specialised 'Private Sub ...etc...' for you.

Here are some common controls:

[controls1.jpg]
fig 1 - some common controls

 


Section 14.1

Naming of Controls

We create controls by dragging them onto a design screen - VB gives them a default name, but this name will not be related to the problem in hand - we should rename them, providing a meaningful name. In addition, a Microsoft convention has grown up that the control should be prefixed by a 3-letter code indicating the type of the control. Here are some of the prefixes:
	lbl		-	label - e.g. lblSalary
	txt		-	textbox - e.g. txtMonth 

However, the main point is to make up a name which conveys what the control is used for, and what type of control it is. The latter is needed because we often have 10 or more controls on a form. For example, a button which deletes something, and a Text box where an age is entered:

DeleteButton
AgeTextBox

We reset the name by altering the name property.  


Section 14.2

Output

See fig 1 for examples of appearance. The following is not a complete list - but here are some output controls: Textbox A textbox can be used for input and output. For just single lines of output, you will normally use a label, but you might wish to display a large amount of text, and even allow the user to alter it - you can use a text box - drag it to hold several lines, set the multi-line property to true, and change the scroll property to both (this adds scroll bars). To produce a new line, we can send the 2 Windows end-of-line characters by: textbox1.text=textbox1.text & vbCrlf 'carriage return+linefeed
Label
We can display text in a label by e.g: label3.Text = "john" Labels (and textBoxes) can be used for static text which is never over-typed. Often we set the background colour to the same colour as the form. We can set the size, colour etc of the text at design time, or at run-time (the former is more common.) Labels cannot be over-typed by the user.  


Section 14.3

Input

See fig 1 again. This shows * button * textbox * radio buttons' - the bullseyes * check boxes * combo box * list box We will not do the detail of every possible control, but will concentrate on the controls useful to get us into programming.  


Section 14.4

button

can be used to initiate a task. Several of them allow the user to make a choice. (menus are also used for this, and are described in the Files chapter.  


Section 14.5

Textbox

The user can key-in data. The text box will be vital for our work, so we look at it in more detail here.

Strings and numbers:- when we input a person's name, for example, this is a string. But when we require a number (e.g. an age) this must be converted from a string to a number with CInt() or CDbl(). So what is the difference between a textbox that has been un-enabled, and a label? Not much! The advantage of a textbox is that the user can copy its text with the mouse (e.g. you may want to copy an error message, and paste it into google - so a textbox is better)  


Section 14.6

textboxes and validation

What if the user keys in a non-numeric item for an age value? Ideally, we should detect this in some way. The easiest way for the programmer is to use the built-in isNumeric function, as in

    dim s as string
    dim i as integer

    s= AgeTextBox.text
    if isNumeric(s) then    ' is string all digits?
         i = s
    else
        MessageBox.Show("error - try again")
    endif

A better way is to reject the non-digits on entry - e.g. by beeping. Also, you might want to detect the 'enter' keypress - both these can be done, but are outside the scope of this unit. Try Help or google - make sure you go for the vb.net version when googling - not plain VB.  


Section 14.7

Radio buttons

These are the circles with a dot in the middle - we have a group of them, and only one can be selected at once. At design time, we can set the Text property - this is the text that goes alongside the button. Yes, they do cause an event when you select them, but normally, something like a button-click takes place, and the program then examines the Checked property, as in:

Private Sub Button1_Click()
If RadioButton1.Checked = True Then
    MessageBox.Show("option 1 selected")
ElseIf RadioButton2.Checked = True Then
    MessageBox.Show("option 2 selected")
End If
End Sub

You will have seen this on a printer setup form, where you select draft, normal, or high quality with options. Then you click ok.

Radios are unusual, in that clicking on one affects another. What if you have 2 sets of radios on one form - one group for selecting pizza size, and one group for selecting topping. Can only one of the radios be set to ON? The answer is yes! - unless you use group boxes.

The group box control is in the Containers section of the toolBox. We put it on the form first, then put related radios inside it. (see in fig 1 at start of chapter). Radios in a group box work independently from other groups.

Here is an example of a data entry form, which invites the user to type their first and last names, and choose whether they are male or female. Clicking OK displays a message box with everything they entered (e.g. John Smith male) here is the form, followed by the code. We have not renamed controls, but it would be useful. Ideally, we should put the radios in a group box.

Problem - suggest new names!

[controls2.jpg]
fig 2 - data entry


Private Sub button1_Click()
Dim answer As String
answer = Textbox1.Text & "-" & Textbox2.Text & "-"
If RadioButton1.Checked = True Then
   answer = answer & "male"
End If
If RadioButton2.Checked = True Then
   answer = answer + "female"
End If
MessageBox.Show(answer)
End Sub

 


Section 14.8

Bounded data and input - Combo box, list box

Imagine you are buying a book over the internet - the web page will ask you for your name, in something like a text box. But when it comes to asking you for your country, it is likely to present you with a drop-down list of countries. This approach provides validation - you can only choose from a pre-set list of items.

The combo box and list box provide this facility for 'bounded' data, but the textbox must be used for your name - 'unbounded' You will see this approach in Microsoft Word - setting font size.

In similar vein, radio buttons allow the user to select one choice - they are 'mutually' exclusive - clicking one unsets the other. Normally you group these together.

Check boxes (rectangular) are similar, but any number of them can be ticked. They do not affect each other.  


Section 14.9

Enabling controls, and Focus

'The user can't make a mistake' - is one approach to a GUI. The use of the enabled property is a powerful aid in this area - we can 'lock out' controls that don't apply at a certain time. Look at Word before a document has been opened - many of the menu options are unavailable - the user is directed down a particular path. We might put:

     Button1.enabled = false

We can also place the cursor in a particular text box, by giving it the 'focus':
     
    AgeTextbox.setFocus

Here is a classic example, which you will see when installing software, or signing up on a website. We force the user to say they have read something before proceeding. (It doesn't matter if they don't actually read it - they just have to say they have for legal reasons.) We make the click of an option button enable the Next button:
[controls3.jpg]
fig 3 - enambling Next when choosing Yes

Initially, we disable the Next button, and we use the checkedChanged event. We also need to handle the No radio button, in case the user tries to be clever by firstly checking Yes (to enable the button) then checking No, hoping that we will leave the next button enabled for them.

Note that CheckedChanged gets called if the user changes a radio from on to off, or from off to on, so we need an IF below, to distinguish between them:


Private Sub yesRadio_CheckedChanged(etc...) 

        If yesRadio.Checked = True Then
            NextButton.Enabled = True
        End If

End Sub
'--------------------------------------------
     
Private Sub noRadio_CheckedChanged(etc...)

        If noRadio.Checked = True Then
            NextButton.Enabled = False
        End If
End Sub

 


Section 14.10

Control Methods and Properties

As well as properties, some controls have methods. These are rather like procedures inside the control. You could imagine properties as variables, but sometimes, the manipulation of a control requires more than simply re-setting one of its variables. We might need to pass several parameters - pieces of data - to a control, and this is difficult with properties.

For example, to at an item at position 5 to a list box:


ShoppingList.Items.Insert(5, "Fish")

Insert is NOT a property, it is a method with some code in it. It is accessed at run-time, not design time.  


Section 14.11

Bike Example

A cycle shop requires the calculation of the weight of a lorry-load of cycles, each identical. Yes, ok - basically the problem is multiplying two numbers together, but we will approach it in a way which illustrates the use of controls. Fig 4 shows the screen we designed. When you create the form, re-name each control AS SOON AS you put it on the form - below - in a table - we provide names for you to use.
[controls4.jpg]
fig 4 bike example

New NameTypePurpose
OneWeightTextBox Text box accepts weight of 1 bike
NumberTextBox Text Box Accepts (whole) number of bikes
ResultTextBox Text Box displays answer
QuitButton Button Ends program
CalcButton Button starts calculation
Here is the code:

'Bike calculation


Private Sub CalcButton_Click(etc...)
    Dim oneWeight As Double
    Dim numOfBikes As Integer
    Dim totalWeight As Double
    
    'get 2 inputs, convert to numbers 
    oneWeight = CDbl(OneWeightTextBox.Text)
    numOfBikes = CInt(NumberTextBox.Text)
    
    ' calculate answer
    totalWeight = numOfBikes * oneWeight
    
    ' display it
    ResultTextBox.Text = CStr(totalWeight)
End Sub
'--------------------------------------------

Private Sub QuitButton_Click(etc...)
    End    ' quit the program
End Sub

Points on the Bike example:

* We used textboxes for input and output. We could have used 'pop-up' input boxes, but our way allows one of the data items to be altered, and a re-calculation done.

* Note the quit button - the end statement stops the program in its tracks.

* There were also other labels (label1, label2...), which we set at design time to show the prompts. We don't refer to them in the code, so have no need to rename them.

* Variables: these are declared and used in the calc procedure - they are local to it. It is unusual to have only locals - this is due to the very small size of the program. Again, we have free choice of names.

The stages in the calculation are:
1. get the data i.e. get the two strings from the text boxes, and convert them to numbers (in this case).
2. Use the variables in the calculation (rather than the controls themselves)
3. Display the result.

* Errors: the program is poor at dealing with wrong input. The user might:


    leave a text box empty
    type non-digits
    type ridiculous numbers

We could improve the program by making extensive checks on the data, and disabling the calculation button until the two values are acceptable. (This is harder than the original problem, so will not do this at such an early stage!).  


Section 14.12

Problems.

1. Run the bike example

2. alter it to use a message box to show the result.

3. ...to use two input boxes for input.

4. ... to tell the user when a negative value is entered - via a message box. You need a IF statement for this.

5. Create a program for converting Celsius to Fahrenheit, and vice-versa. Here are the formulae:

        c to f:
            f = c*9/5 +32

        f to c:
            c = (f-32) * 5/9

    note that in VB , 9/5  gives 1.8 - not an integer answer as it does in C++, Java

Module Admin   Contents, Index