Wednesday, October 13, 2010

VB Lesson2 for SYBCA Students

What an event?

The ‘look’ of a Visual Basic application is determined by what controls are used, but the ‘feel’ is determined by the events. An event is something which can happen to a control. For example, a user can click on a button, change a text box, or resize a form. As explained in Creating a Visual Basic Application, writing a program is made up of three events: 1) select suitable controls, 2) set the properties, and 3) write the code. It is at the code writing stage when it becomes important to choose appropriate events for each control. To do this double click on the control the event will be used for, or click on the icon in the project window (usually top right of screen). A code window should now be displayed similar to the one shown below.

The left hand dropdown box provides a list of all controls used by the current form, the form itself, and a special section called General Declarations. The corresponding dropdown box on the right displays a list of all events applicable to the current control (as specified by the left hand dropdown box). Events displayed in bold signify that code has already been written for them, unbold events are unused. To demonstrate that different events can play a significant role in determining the feel of an application, a small example program will be written to add two numbers together and display the answer. The first solution to this problem will use the click event of a command button, while the second will the change event of two text boxes.

Click Event

Before any events can be coded it is necessary to design the interface from suitable controls. As shown in the screen shot below use: 2 text boxes to enter the numbers, a label for the ‘+’ sign, a command button for the ‘=’ sign, and another label for the answer.
Making the click event is very simple just select the button with the mouse and double click visual basic will generate
You can see on the top right there is a 'click' dropdown list this is known as a event handler.

Writing your own even

In the first example the user has to enter two numbers and then click on the equals button to produce an answer. However, the program can be changed so that the answer will be calculated every time either of the two numbers are changed without requiring an equals button.
To do this first remove the equals command button and replace it with a label with the caption set to ‘=’. Now, bring up a code window and copy to the Windows clipboard the line lblAnswer = Str$(Val(txtNumber1.Text) + Val(txtNumber2.Text)). Using the left hand dropdown box select the first text box and then select the Change event from the right dropdown box. Then paste the code from the clipboard into the empty subroutine. Select the second text box and do the same. The same line is required twice because the two click events belong to two separate controls. The final code should look like:
Private Sub txtNumber1_Change()
    label2.Caption = Str$(Val(text1.Text) + Val(text.Text))
  End Sub

  Private Sub txtNumber2_Change()
    label2.Caption = Str$(Val(text1.Text) + Val(text2.Text))
  End Sub
Run the program again, enter the two numbers and observe what happens. Each time a digit changes the answer is recalculated.
Note: There may be times when recalculating more advanced problems takes too long on each change and so requiring the user to enter all the data first and then click on an answer button might more appropriate.

Using the event GotFocus event

So far only one event has been used per control, however this does not have to be the case! Add a StatusBar control to the bottom of the form, bring up the code window using , select the first text box (txtNumber1) from the left hand dropdown box, and then select the GotFocus event from the right hand dropdown box. Now some basic instructions can be written in the status bar so that when the cursor is in the text box (the text box has focus) the status bar reads “Enter the first number”. After completing this change to the second text box and using the same GotFocus event change the statusbar text to “Enter a second number”. The code to set the status bar can be seen below.

CheckBoxes

Option bars are used quite often in the windows environment as they can only have two outputs 0 and 1 these get used to process the form. In this example it will be used to change the some text from normal to bold or to italic.
Private Sub chkBold_Click()
If chkBold.Value = 1 Then ' If checked.
txtDisplay.FontBold = True
Else ' If not checked.
txtDisplay.FontBold = False
End If
End Sub

Private Sub chkItalic_Click()
If chkItalic.Value = 1 Then ' If checked.
txtDisplay.FontItalic = True
Else ' If not checked.
txtDisplay.FontItalic = False
End If
End Sub

This example can be found at "smaples/PGuide/controls/Controls.vbp" or downloaded free from the download page.
The checkboxes can be turned on at runtime by simply typing
name.value = 1 ' 1 On , 0 off
Note: If you create the frame first and then add the option buttons by single clicking on the toolbox and dragging the cross hair cursor on the frame to create the controls, they will be attached to the frame and will move with it if you decide to re-position the frame. Notice, however, that if you create the frame first and double click the screen controls, then drag them from the centre of the form on to the frame, they will not be attached to it and will be left behind when you try to move the frame. Try this out.
Notice that when you run your application the same icon is loaded first (probably the clipboard, if you created that option button first). You can alter the option that has the focus first, by selecting one of the other option buttons and setting its property tabindex to 1.

Option Buttons

Changing the background colour

Changing the background colour gets used mostly by freeware, or the type of programs you generate for use with banners or adverts, anyway it might come in useful sometime. This example shows an ordinary picture of a smiley face then I put in some nice background colours to make it stand out more.

Private Sub Form_Load()
BackColor = QBColor(Rnd * 15)
ForeColor = QBColor(Rnd * 10)
Picture1.BackColor = QBColor(Rnd * 15)
Picture1.ForeColor = QBColor(Rnd * 10)
End Sub

List boxes

Note :
List boxes and combo boxes are used to supply a list of options to the user. The toolbox icons representing these two controls are for list box and for combo box.
A list box is used when the user is to be presented with a fixed set of selections (i.e. a choice must be made only from the items displayed, there is no possibility of the user typing in an alternative).
Examples might be offering a list of the days in a week, the available modules in an elective catalogue, the holiday destinations available from a particular airport or the types of treatment offered by a beauty salon.
To create a list box, double click on the toolbox icon . Drag the resulting box into place on the form and size it according to the data it will hold. The left hand picture below shows a list box that has been created and sized on Form1. In the middle is the code that is required to load a selection of cars into the list. The data has been included in the procedure Sub Form_Load so that it appears when Form1 is loaded. Finally, the picture on the right shows what appears on the form when the application is run. Notice that vertical scroll bars are added automatically if the list box is not deep enough to display all the choices.

If you however add the following source code to this project

Add to a Lisbox


Private Sub Form_Load() List1.AddItem "Monday"
List1.AddItem "Tuesday"
List1.AddItem "Wedsday"
List1.AddItem "Thursday"
List1.AddItem "Friday"
List1.AddItem "Saturday"
List1.AddItem "Sunday"
End Sub The source code should look somthing like this :


Removing & Advanced Options

Note: They appear in the order they were typed if you changed the properties window by changing sort order = true then they will go into alpaetical order. List items can be added and deleted all the list is counted as the order they are in so for exapmple if you wanted to delete "Tuesday" you would type list1.RemoveItem 1
And to add to the list in a paticular order just add
list1.additem "My Day", 5
This will be added after saturday.
And finally to clear the lisbox type
List1.clear This will completly clear the contence of the listbox.
Note: The property ListCount stores the number of items in a list, so list1.ListCount can be used to determine the number of items in list box list1.
The property ListIndex gives the index of the currently selected list item. So the statement list1.RemoveItem List1.ListIndex removes the currently highlighted list item.
Adding an item can be accomplished very neatly using an input dialog box. Try this:
list1.AddItem InputBox("Enter a day", "Add a Day")
This will open a message box and prompt you for a new day to enter this will then be added to the list index at the bottem unless you specify were it should go.

Combo Boxes

Combo boxes are of three types (0,1 and 2), setting their properties/styles determines the type. Combo boxes (style 0 and 2 ) are a good choice if space is limited, becaue the full list is displayed as a drop down list, it does not occupy screen space until the down arrow is clicked. Picture of combo box style 0

The user can either enter text in the edit field or select from the list of items by clicking on the (detached) down arrow to the right. The drop-down Combo box, list is viewed by clicking on the down arrow. This type of combo box does not have a down arrow because the list is displayed at all times. If there are more items than can be shown in the size of box you have drawn, vertical scroll bars are automatically added. As with previous type, users can enter text in the edit field.
Drop-down List box (Style=2)
It is slightly confusing to find this control under combo box. This control behaves like a regular list box except that the choices are not revealed until the down arrow is clicked. The user can select only from the choices given, there is no text entry facility.
Note: Combo boxes of style 0 and 2 cannot respond to double click events.

No comments:

Post a Comment