Visual Basic - Understanding Controls - Part I

11 minute read

Visual Basic programming can be said as programming the controls that are used in the form.  But behind the curtains, there are some fundamental programming concepts on the basis of which our project is built.  We shall cover if-elsestatement as this shall be used in this article.


If-else statement

If expression Then
    ‘Do this
ElseIf expression2 Then
    ‘Do this

    ‘Default if none of the above conditions is true.

End If


The if-else block starts with If statement and ends with an End If statement.  When the expression in the statement proves to be true, the statements written just next to Then are executed.


Two or more conditions can also form an expression using And, Or, Xor, Not operators.


Table 1: Expressions in If-Else Statement.




a=2 And b=3

a=2 and b=3 then only statements are executed

a=2 Or b=3

a=2 or b=3 or both are true, then only statements are executed

a=2 Xor b=3

Either a=2 or b=3 then only statements are executed.

Not a

When a assumes a non-zero value, then statements are executed




Just as in other languages like C, there is scanf() and in BASIC its input command; there’s a text box through which one can input values to the program.  Using Visual Basic, gives us an added advantage of displaying text entered as Bold, Italics or Underlined.


The text entered in the TextBox is stored in its Text property.  To access a TextBox with Name txtName, we need to code as


MsgBox txtName.text


Here, the command MsgBox prompts the value of text (String) entered by user. The dot “.” operator is used to access the properties of the control desired.




Figure 1: Accessing Properties of a control


To convert String data into Integer data, we use val() function as shown below.  Thereafter, we can perform any mathematical operations on the converted data.


Dim age as Integer

age = val(txtAge.text)


The text entered by the user can be aligned to Left, Right or Center.  This is done by using Alignment property.  The maximum number of characters a text box can accept can be defined in MaxLength property of the same.  By default, its value is 0, which states that the max length is not defined. We can select the text in the TextBox and this text is stored in SelText Property, while SelLength indicates the length of the number of characters in the selected text.


The PasswordChar Property is set to a symbol (normally *) to enter password(hidden text).  To have Multiple Line text boxes, in order to have data such as address, we can set MultiLine property as true. We can also add scrollbars by using the ScrollBars Property.


There are various events that are generated when a user types anything/clicks on the text box. They are as,


Table 2: Commonly Used Events (*also used in other controls)



Activated When


User clicks on an object (here TextBox)


User double clicks on an object (here TextBox)


As soon as a key is pressed or on every stroke of keyboard

KeyPress(KeyAscii As Integer)*

As soon as a key is pressed or on every stroke of keyboard.  The ASCII value of the keypressed is stored in KeyAscii



When the TextBox gains/loses focus from/to another object, this event is activated.



Limitation of TextBox:

We cannot change the font of a selected text. The font of the entire text box changes. This can be removed by using RTF TextBox.



To Remember:

It is not preferable to use a TextBox to display text; rather a Label should be used.  In case, one uses text box for same, TextBox property of Enable should be kept False.




A label is use to display some information on the screen (here the form).  It has same properties as of TextBox but its functionality is different.  To avoid confusions between the form color and the label color (which is normally preferred to be same), the BackStyle property is set to Transparent, which renders the backcolor of label as that of form. We can make the label appear just like a TextBox by changing its display properties by setting the BorderStyle property as Fixed Single and BackColor property as White.




Figure 2: Different forms of Label


Though they both appear the same, we can’t input text from user in lblOne.  The other forms of label are lblTwo and lblThree (available by altering the above mentioned properties.)


The text visible as label is set in the Caption property of label.

Wordwrap property expands vertically or horizontally to fit the text specified in its Caption property provided Autosize property is set True. (See lblThree)




The button’s such as Ok, Yes and No that we often see in windows, are command buttons. These buttons normally have a shortcut key to access them such as ALT + O for Ok. To create such shortcut keys for command buttons, we need to place ‘&’ (Ampersand) symbol before a specific character in the Caption Property.  Few such examples are illustrated in Table 3.  The (object) name should have a prefix cmd as a standard.


Table 3: Setting Caption of CommandButton


Caption Property

Shortcut Key








Save &As






Figure 3: Forms of CommandButton

The command button can be of two types; Standard and Graphical.  The Graphical form allows us to have a colored or a bitmap as command display.  This can be defined in Style Property.  The BackColor property defines the color of the command button in case of graphical form if we wish to keep.  The first command button (Exit) in Figure 3 is Standard and the second one (Help) is Graphical.


We can disable a button by setting Enabled property as False.  As said earlier, when an object is used by the user, one or many events are activated.  When a user clicks on the command button, Click Event (default) is activated.  A sample code for Exit button is as,


Private Sub cmdExit_Click()

Unload Me

End Sub


Here, Unload Me signifies to unload the form on which the Exit Button is placed.  To exit the complete application (our project), one can modify the code as,


Private Sub cmdExit_Click()


End Sub


Often, we need to define the order of access to CommandButton through Tab Key.  In that case, the TabIndex property should be set to the sequence order of the access.


In many applications, like Calculator or Tic Tac Toe, there are various command buttons that share same properties.  In that case, we can create an array of CommandButton. 


For example,



Figure 4: Calculator Program

Here, when a user presses on any number, the text in the Navy Blue label (lblTyped) gets appended by the key pressed.


Thus, text appended is the caption of the command buttons. So, we can define an array of CommandButtons here.


To define an array, we need to change the Index Property of CommandButtons that share the same name (here cmdValue)


Thus, we can refer to a specific command button by its UNIQUE Index number as,


cmdValue(3) points to ‘3’ (which is currently selected). Please refer to the code written below.


Private Sub cmdValue_Click(Index As Integer)

lblTyped.Caption = lblTyped.Caption + cmdValue(Index).Caption

End Sub


This helps us to have compact code and better readability.  In case, the function is not that simple we can use condition based programming on the value of Index.  We shall cover condition based programming in the coming articles. A Sample Code is still mentioned below,


Private Sub cmdOP_Click(Index As Integer)


If cmdOP(Index).Caption = "+" Then

    operator = "+"

ElseIf cmdOP(Index).Caption = "-" Then

    operator = "-"

ElseIf cmdOP(Index).Caption = "*" Then

    operator = "*"

ElseIf cmdOP(Index).Caption = "/" Then

    operator = "/"

ElseIf cmdOP(Index).Caption = "=" Then

    operator = "="

End If


End Sub


In Windows, when we place our mouse over the command button, often a tool tip is displayed.  This tool tip is a form of help indicating the function of the command button.  This can be added by writing the text in ToolTipText Property.  This can also be changed dynamically when the program is executed as,


Private Sub Form_Load()

cmdOP(Index).ToolTipText = "Operator is " + cmdOP(Index).Caption

End Sub


The visibility of CommandButton can be kept false by changing its Visible property to False.  This is generally used when we need to restrict the user’s ability to perform some functions. We see this commonly in demo versions of software, where the programmer has disabled some features.  This property (of Visibility) is common to all the objects in Visual Basic.



A frame is basically used to separate controls used in our form.  There’s hardly anything to code for a frame but it’s used to increase the functionality of program and give a professional touch to it.




Figure 5: Frame AM used in the above case.


By using frames, we can group controls as per their functions.  Using frames, we can create more than one group of option buttons in one form.  An example of frame is shown in Figure 5.  The name of the frame is mentioned in the Caption property of frame.  Here, its value is set to AM.

Option Button


Option Buttons are used when the user is allowed to choose one from the many available choices.  Many authors refer option buttons as Radio Buttons.  They act as a Boolean operators and when a user clicks on them, they assume either True or False condition.


Private Sub optChoice_Click()

If optChoice.Value = True Then

      ‘do when it is clicked

ElseIf optChoice.Value = False then

      ‘do this when not clicked

End If

End Sub


The Value property returns Boolean value indicating whether the button is clicked or not (True or False).




Figure 6: Use of Option Buttons



The window (Figure 6) above has options like Resistance, Inductance, Capacitance in a group; Series and Parallel in another group. These are option buttons. 



To Remember:

All option buttons on a form as such form one group but by using a frame, we can have various groups on a single form.



Private Sub cmdCalculate_Click()

a = Val(txtVal1.text)

b = Val(txtVal2.text)

c = Val(txtVal3.text)

If a = 0 Or b = 0 Or c = 0 Then

    If (optRes = True Or optInd = True) And optParallel = True Then

        MsgBox ("Cant Proceed Ahead. Division by Zero..")


    ElseIf optCap = True And optSeries = True Then

        MsgBox ("Cant Proceed Ahead. Division by Zero..")


    End If

End If


If optSeries = False And optParallel = False Then

        MsgBox ("OptSeries / OptParallel Option Not Chosen. Please _                Choose a option")

End If



If (optRes = True Or optInd = True) And optSeries = True Then

    ans = a + b + c

ElseIf (optRes = True Or optInd = True) And optParallel = True Then

    ans = (a * b * c) / (a * b + b * c + c * a)

ElseIf optCap = True And optSeries = True Then

    ans = (a * b * c) / (a * b + b * c + c * a)

ElseIf optCap = True And optParallel = True Then

    ans = a + b + c

End If

lblAns.Caption = ans

End Sub


An array of option button under one group is generally preferred.  Based on the combination of the two groups of option buttons, an action is taken and answer (lblAns) is calculated accordingly.

Check Box


There’s a small line that differentiates the functionality of check boxes from option buttons.  The user can choose more than one option rather just one, which was the case in option button.  Check boxes returns 1 (not True) when it is selected. 




Figure 7: Illustration of Check boxes


Here, we have used two check boxes with the Caption Property set to Remember Me and Remember My Password respectively.  The code for this would appear like,


Private Sub chkRememberMe_Click()

If Check1.Value = 1 Then

      ‘code for remembering username.

      ‘we are skipping the code as we need to refer to database                     management (which shall be covered later).

      ‘there is no need of else statement as there’s no processing                  needed in other case.

End If

End Sub


The other properties are similar to Option Buttons.




Sometimes, there’s a need to execute a specific task repeatedly after specified time.  Timer Control helps us do the same.  Using the Interval property of Timer, we can set the time interval after which the task has to be performed.  This Interval is defined in terms of milliseconds. The default interval is 0. The timer control when placed on form, doesn’t appear visible while execution.


The code to be executed when the time has elapsed is to be written in,


Private Sub Timer1_Timer()

    Counter = Counter + 1

        If Counter >= 20 Then

        'Execute the Sequence Mentioned

        'this is executed after timer has been activted 20 times.

        'i.e. 20 * Time Interval

        End If

End Sub



To Remember:

The timer is activated only if it Enable property is kept True. This is useful when we need to start timer after a specific instance.


Some of the most visible application of Timer include, providing delay at the start of an application, calculating processing time of a machine and in engineering plants to sample data.

Note: This series was first published in DeveloperIQ and was co-authored by Puneet Ghanshani with Pranjali Bakeri in 2005-2006.