Visual Basic - Understanding Controls - Part II
In our previous article, we considered few of the many controls in Visual Basic. In this article, we aim at understanding other standard controls and basic programming techniques and standard statements.
Controls Continued
ListBox
We have seen two methods to provide choices to user i.e. by using Option Buttons and CheckBoxes. But both Option buttons as well as Check boxes fail when the number of options exceeds a certain limit as they are bound to go out of the screen. List boxes can be an alibi for the same.
There are two ways to set the items / choices of the ListBox. Once the number of items is fixed, we can add them in the List property and hence can populate the list. The other method to add items in the list is to add dynamically through our code. Both methods are illustrated in Figure 1.
Figure 1: Two Methods of Setting List
After having the items in the list, the focus is to find out which option has been selected by the user. There are again two methods to do the same (Table 1).
Table 1: List Box Access Methods
Method One: Referring the items by ListIndex property |
Method Two: Referring the items by Text property |
Private Sub lstOptions_Click() If lstOptions.ListIndex = 0 Then MsgBox lstOptions.Text End If End Sub |
Private Sub lstOptions_Click() If lstOptions.Text = "Item1" Then MsgBox lstOptions.Text End If End Sub |
In the first method, the list items are referred by the index number which starts from 0 to n-1, where n = total number of items, given by the ListCount property. While in the second method, we refer the items by the Text property.
Figure 2: Scrollbar in ListBox |
The scrollbars are automatically added once the number of item exceed the number that can fit in the area of the ListBox, which is shown in
|
We can remove the items dynamically by using RemoveItem(integer) as shown below. To remove all the items, we can use the function Clear()
Figure 3: Remove & Clear |
‘Clears complete list Private Sub cmdClear_Click() lstOptions.Clear End Sub
‘Removes Specific Item from List Private Sub cmdRemove_Click() lstOptions.RemoveItem (lstOptions.ListIndex) End Sub
|
There are some other baby versions of ListBox. One of the modifications allows us to have list of check boxes in list. This can be done by setting the value of Style property as 1-Checkbox. The other version allows us to have multiple selections in a list. This is done by setting MultiSelect property to 1-Simple. The user can hence select or deselect any item in the list. By setting its value to 2-Extended, the user can use shift key to select multiple items at a stroke. Both the versions are illustrated in Figure 4.
|
|
Figure 4: Different Versions of ListBox |
The number of selected items can be known through the SelCount property of the ListBox. We can also have one more version having more than one columns, which can be set by Columns property to a numeric value greater than 0. This adds a horizontal scrollbar if the list does not entirely fit. By using the Sorted property to True, we can alphabetically sort the list.
ComboBoxes
ComboBoxes are similar to ListBoxes with few limitations like we can not have multiple columns in ComboBoxes. The procedure to add/remove/clear the items in the ComboBoxes is similar to that of ListBox. The benefit of using ComboBox is that it occupies lesser space than ListBox with same number of items.
Figure 5: ComboBox Example |
Secondly, ComboBox displays just one item and on clicking the drop box, the other items are visible. The same example of ListBox is implemented using ComboBox, which is shown in Figure 5.
|
When the Locked property is set to True, the user can see the drop down list but can not select any item from the ComboBox.
ScrollBars
There are two types of ScrollBars i.e. Horizontal and Vertical Scrollbars. The range of the ScrollBar can be set to the Min and Max properties of the Scrollbar. The current position of the slider in the scrollbar is indicated by Value property.
When the arrows of the scrollbars are clicked, the value of the scrollbar changes by an amount as defined in the SmallChange property. When the user clicks on the area between the slider and the arrow, the value changes by an amount as defined in the LargeChange property.
Figure 6: Illustration of Scrollbar |
Private Sub HScroll1_Change() txtValue.Text = HScroll1.Value End Sub
Here, the range is 0 – 100. |
Depending upon the value of scrollbar, either a text or picture can be rotated. One such application is file explorer (like Windows Explorer).
Picture Box & Image Box
A picture box is used to display picture that is mentioned in Picture property. If the size of the picture is bigger than the Picture Box, then the picture is not compressed and we can see only a small part of the picture. Setting the AutoSize property to True re-sizes the picture box to adjust to the picture size.
Figure 7: PictureBox and ImageBox Illustration |
The acceptable forms of pictures in picture box are .BMP, .GIF, .JPG, .WMF and .ICO. Animated picture file(s) will not animate on the form. The similar function is done by ImageBox with few exceptions. The ImageBox has Stretch property. When Stretch property is False, ImageBox acts like PictureBox and when Stretch property is True, the picture gets compressed into pre-decided area of ImageBox.
To Remember: The difference can be seen in the Figure 7. The original image is 800x600 pixel image. In the picture box, part of the picture that can fit into the box, while in the second case, the complete image is compressed to fit into the same space. However, this might result into distortion of the Image. |
We can assign the picture in the ImageBox and the PictureBox dynamically by LoadPicture() function as shown below
Private Sub Form_Load()
Picture1.Picture = LoadPicture("C:\Pictures\17.jpg")
End Sub
Private Sub cmdReset_Click()
Picture1.Picture = LoadPicture("")
‘this removes the picture fromPictureBox
End Sub
Another method is to use Cls Property as Picture1.Cls instead of
Picture1.Picture = LoadPicture(“”)
One of the most important applications in Image Processing is accessing the pixels of picture box. The color of the pixel can be obtained by Point function.
Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X _ As Single, Y As Single)
Form1.BackColor = Picture1.Point(X, Y)
End Sub
In the above code, the color of the form changes to the color of the pixel where the mouse is clicked.
Various commands associated with picture are listed below:
Table 2: Different Commands associated with PictureBox
Purpose |
Command / Property |
||||||
Printing |
Printer.PaintPicture picture x1, y1 |
||||||
Scaling |
ScaleMode |
||||||
Saving |
SavePicture picture, filename |
||||||
Clipboard Related Functions |
|
||||||
Printing Text in PictureBox |
Picture.Print(“text here”) The position of the text is defined by Picture.CurrentX and Picture.CurrentY |
||||||
Graphic Functions |
Pset for setting point Circle for drawing circle Line for drawing line |
Coding Fundamentals
Let’s understand the fundamentals of coding. In the first article, the declaration of variables was considered. While declaration, we were defining the type of variable. In case we forget to define the variable, still the program would execute but may result into erroneous or unexpected results. To avoid such complicacies, we place Option Explicit in the General Declaration Section of the form code.
While declarations of variables or constants, we sometimes need to assign the values to them, which can be done by two methods,
Table 3: Initialization of Variables
Method 1 |
Method 2 (Has become obsolete) |
Dim name as String name = “Visual Basic” |
Dim name as String Let name = “Visual Basic” |
Setting properties of controls
Setting properties of a specific control can be done by two methods. Both are illustrated below:
Table 4: With … End With Block
Method 1 (Has become obsolete) |
Method 2 |
Text1.Text = "VB" Text1.BackColor = vbBlue Text1.ForeColor = vbWhite Text1.MaxLength = 20 |
With Text1 .Text = "VB" .BackColor = vbBlue .ForeColor = vbWhite .MaxLength = 20 End With |
As shown above, the first method uses repetition of the control name, while the second method uses With…End With block
Suppose we need to set the properties of a control in some other form (with name FormName) apart from the form in which we are working, we use exclamation ‘!’ operator as,
With FormName!ControlName
….
….
….
End With
This can be used to change the properties of a control on the based of conditions in form calling the called form.
Commenting
To comment means to describe the purpose of the statement or function used in our code. The comments are not visible to the user of the program but they increase the readability of the program. These lines are not compiled by our compiler and hence commenting doesn’t increase the size of our executable file.
There are two methods to comment in Visual Basic,
Method 1: Use of apostrophe
Use of apostrophe (’) before the comment statement
lblDate.Caption = "Date: " + Date$
'This displays today's date as in System
Method 2: Use of Rem Statement.
lblDate.Caption = "Date: " + Date$
Rem This displays today's date as in System
This method was been used in earlier times of BASIC Programming and was later adopted in Visual Basic Programming. But this method has now become obsolete.
Breaking Lengthy Statements
When the statement (a piece of code) is too long, it can be broken into two or more parts using underscore (_) operator. The underscore operator can be placed in between the statement and the next statement can be broken down on the next line. Note the indentation done, which improves readability of the code. This can be illustrated as,
If (txtA = "a" And txtB = "b" And txtC = "c") Or _
(txtA = "b" And txtB = "c" And txtC = "a") Then
‘See the use of underscore operator
MsgBox "work done"
End If
Limitation: |
Multiple Statements on a Line
It is possible to have more than one statement on a single line. The compiler differentiates the two statements by a colon (:).
Table 5: Multiple Statements on Line
Normal Method |
Multiple Statements on a line |
For i=1 to 10 x(i) = 7*i Next |
For i=1 to 10: x(i) = 7*i: Next
|
Considering Error Conditions
While runtime, there are some unpredictable errors that can occur. These errors hinder the successful execution of our program. To avoid this, we include a statement On Error in the function through which there are possibilities of generation of error.
The syntax of this statement is
On Error Goto label
On Error Resume Next
On Error Goto 0
On occurrence of error the first statement causes a jump in flow of execution to an existing label in the same function. The second statement causes the next statement to be executed, hence ignoring the error. The third statement discards any error occurring at the time of execution of program.
One such example is shown below,
Private Sub Command1_Click()
On Error Goto to ErrorHandler
….
….
‘code follows here
ErrorHandler:
Msgbox err.description
End Sub
This type of coding has a flaw. Even if there are no errors while execution, the statements of ErrorHandler label are executed. To avoid this, we include another statement Exit Sub before ErrorHandler.
Private Sub Command1_Click()
On Error Goto to ErrorHandler
….
….
‘code follows here
Exit Sub ‘breaks the flow of execution
ErrorHandler:
Msgbox err.description
End Sub
Multiple Forms
In a project having multiple forms, we can define the startup form, which should be displayed the first. This is done by Project Properties in the Project Menu.
Figure 8: Project Properties
Along with the startup form, we can set project description and Project Name (here, ESystems) that should be displayed as the Title of the Message Box.
In our next article, we aim to cover few advanced controls in Visual Basic and their coding.