Visual Basic Demystified - II

Visual Basic programming can be said as programming the controls that are used in forms. However, behind the curtains, there are some fundamental programming concepts on the basis of which our project is built. In this part, we will cover if-else statement.

If-else statement

If expression Then
‘Do this
ElseIf expression2 Then
‘Do this
Else
‘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. Whenever the expression in the statement proves to be true, statement/s written after ‘Then’ are executed.

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

Expression

Interpretation

a=2 And b=3

Only if a=2 and b=3 will the statements be executed.

a=2 Or b=3

Only when one side or the other is true will the statements be executed.

a=2 Xor b=3

One side or other must be true but not both.

Not a

When 'a' assumes a non-zero value, only then are the statements executed.

 Table 1: Expressions in If-Else statement

CONTROLS

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

Text entered in the TextBox is stored in this control’s 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 the user. Dot “.” operator is used to access the properties of the control desired. Refer figure 1.



Figure 1: Accessing the 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)

Text entered by the user can be aligned to Left, Right or Center. This is achieved using Alignment property. The maximum number of characters that a text box can accept can be defined in MaxLength property of the same. By default its value is 0, which states that the maximum 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. See table 2.

Event

Activated When

Click*

User clicks on an object (here TextBox).

DblClick*

User double clicks on an object (here TextBox).

Change

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

KeyPress (KeyAscii As Integer)*

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

GotFocus
LostFocus*

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

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



Label

A label is used to display information on the screen (here the form). Though its properties are akin to that of a TextBox, they differ in functionality (figure 2). To avoid confusion between form color and 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 the form. We can make the label appear just like a TextBox by changing its display properties. Set BorderStyle property as Fixed Single and BackColor property as White.



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

Text visible as label is set using Caption property of label.

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

CommandButton

Buttons 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 examples are illustrated in table 3. The (object) name should have the prefix cmd as standard.

Caption Property

Shortcut Key

Name

&File

ALT + F

cmdFile

E&xit

ALT + X

cmdExit

Save &As

ALT + A

cmdSaveAs

Table 3: Setting Caption of CommandButton

Command button are of two types – Standard and Graphical. The latter form allows us to exhibit colors or a bitmap image as command display. This can be defined in Style property. Also, BackColor property defines the color of the command button.

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, whenever a user uses an object, 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 given below:

Private Sub cmdExit_Click()
Unload Me
End Sub


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

Private Sub cmdExit_Click()
End
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 the same properties. In such cases, we can create an array of CommandButton. Let us look at an example.



In figure 4, when a user presses on any number, the text in the Navy Blue label (lblTyped) will be 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 a common 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 snippet below.

Private Sub cmdValue_Click(Index As Integer)
lblTyped.Caption = lblTyped.Caption + cmdValue(Index).Caption
End Sub


As such, it is possible to have a compact code, which enables better readability. In case the function is of a complex nature, we can use condition-based programming on the Index value. We shall look at condition-based programming in the forthcoming articles. Check out code 1, a sample code!

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 a command button, we often see a tool tip displayed. The 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 objects in VB.

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


By using frames, we can group controls according to their functions. Frames allow us to create more than one group of option buttons in a single 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 select one from the available choices. Many authors refer option buttons as Radio Buttons. They act as Boolean operators and when a user clicks on them, they assume either True or False condition. Refer code 2.

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).



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



Check out code 3.

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..")
End
ElseIf optCap = True And optSeries = True Then
MsgBox ("Cant Proceed Ahead. Division by Zero..")
End
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, action is taken and an answer (lblAns) calculated accordingly.

Check Box

A narrow line differentiates the functionality of check boxes from that of option buttons. The user can choose more than one option, unlike in the case of the option button. Check boxes return 1 (not True) when it is selected.



In figure 7, we have used two check boxes with the Caption property set to Remember Me and Remember My Password, respectively. Refer code 4.

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.

Timer

Sometimes a specific task may have to be executed repeatedly after a specified time. In such scenarios, the Timer control will be of immense help. Using the Interval property of Timer, we can set the time interval (defined in terms of milliseconds) after which the task has to be performed. The default interval is 0.

The timer control, when placed on a form, will not be visible during execution. Code 5 provides a veritable example.

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




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

The authors are currently pursuing Instrumentation and Control Engineering at the Nirma Institute of Technology, Ahmedabad. They can be contacted at: punit.ganshani@gmail.com and pranjali.bakeri@gmail.com.




Added on December 2, 2007 Comment

Comments

Post a comment