Gui Unit 3
Gui Unit 3
DECISION MAKING
Decision Statements (Conditional Statement)
Applications need a mechanism to test conditions, and they take a different course of
action depending of the outcome of the test. Visual Basic Provides three statement that
allow you to alter the course of the application based on the outcome of a condition:
If…Then
If…Then…Else
Select Case
IF…THEN STATEMENTS
The If…Then statement tests an expression, which is known as a condition. If the
condition is true, the program executes the statement(s) that follow the Then keyword up
to the End If statement, which terminates the conditional statement. The If…Then
statement can have a single-line or a multiple-line syntax. To execute one statement
conditionally, use the single-line syntax as follows:
If condition then statement
To execute multiple statements conditionally, embed the statements within an If and
End If statement, as follows:
If condition Then
` Statement
` Statement
End If
Conditions are logical expressions that evaluate to a True/False value and they
usually contain comparison operators-equals (=), different (<>), less than (<), greater
than (>), less than or equal to (<=), and so on-and logical operators-And, Or, Xor, and Not.
Here are a few examples of valid conditions:
If (age1 < age2) And (age1 > 12) Then …
If score1 = score2 Then …
The parentheses are not really needed in the first sample expression, but they make
the code a little easier to read and understand.
The expressions can get quite complicated. The following expression evaluates to
True if the date1 variable represents a date earlier than the year 2005 and either one of
the score1 and score2 variables exceeds 90:
If (date1 < #1/1/2005) And (score1 >90 or score2 > 90) Then
` statements
End If
IF…THEN…ELSE STATEMENTS
A variation of the If…Then statement is If…Then…Else statement, which executes the first
block of statements if the condition is True and another block of statements if the
condition is False. The syntax of the If…Then...Else statement is as follows:
If condition Then
statementblock1
Else
statementblock2
End If
LOOP STATEMENTS
Loop statements allow you to execute one or more lines of code repetitively. Many task
consists of operation that must be repeated over and over again, and loop statements are
an important part of any programming language. Visual Basic supports the following loop
statements:
For..Next
Do…loop
While …End while
FOR NEXT LOOP
Unlike the other two loops, the For …Next loop requires that you know the number of
time that the statement in the loop will be executed. The For…Next loop has the following
syntax:
For counter = start to end [Step increment]
‘ statements
Next [counter]
The keywords in the square brackets are optional. The arguments counter, start, end and
increment are all numeric. The loop is executed as many times as required for the counter
variable’s value to reach ( or exeed) the end value, The variable that appears next to the
For In executing a For…Next loop, Visual basic does the following:
1. Set the counter variable equal to the start variable (this is the control variable’s
initial value).
2. Test to see whether counter is greater than end. If so it exists the loop without
executing the statements in the loop’s body, not even once. If increment is
negative, Visual Basic tests to whether the counter value is less than the end value.
If it is it exist the loop.
The For..Next loop scans all the elements of the numeric array data and calculates their
average.
Iterating an array with a For next loop
Dim I As Integer, total as Double
For i=0 To data.Length
Total = total+data(i)
Next i
Debug,Writeline (total/ Data.Length)
You can iterate through the month names with a For Each loop like one that follows:
For each month As String in months
Debug.Writeline(month)
Next
The month control variable need not be declared if the infer option is on. The
compiler will figure out the type
DO Loops
The Do Loop statement executes a block of statements for as long as the condition
is True or until a condition becomes True. Visual Basic evaluates an expression, and if it’s
True, the statements in the loop body are executed. The expression is evaluated either at
the beginning of the loop or at the end of the loop. If the expression is False, the program’s
execution continues with the statement following the loop. These two variations use the
keywords While and Until to specify how long the statement will be executed. To execute a
block of statements while a condition is True, use the following syntax:
Do While condition
Statement-block
Loop
To execute a block of statements until the condition becomes True, use the following
syntax:
Do Until condition
Statement-block
Loop
When Visual Basic executes these loops, it first evaluates condition. If condition is
False, a Do…While loop is skipped but a Do…Until loop is executed. When the loop
statement is reached, Visual Basic evaluates the expression again; it repeats the statement
2. Do Until intX = 3
intX += 1
Loop
and
3. Do
intX += 1
Loop Until intX = 3
While Loops
The While...End While loop executes a block of statements as long as a condition is
True. The has the following syntax:
While condition
Statement-block
End While
If condition is True , the statements in the block are executed. When the End While
statement is reached, control is return to the While statement, which evaluates condition
again. If condition is still True, the process is repeated. If condition is False, the program
resumes with the statement following End While.
The loop is below prompts the user for numeric data. The user can type a negative
value to indicate he’s done entering values and terminate the loop. As long as the user
enters positive numeric values, the program keeps adding them to the total variable.
LISTING: Reading an unknown number of values
Dim number, total As Double
Number = 0
While number => 0
total = total +number
number = InputBox(“Please another value”)
End while
Sometimes you may need to continue with the following Iteration instead of exiting the
loop(in other words, skip the body of the loop and continue with the following value). In
these cases, you can use the Continue statement (Continue For for For….next loops,
Continue while for while loops, and so on.
VB.Net- STRING
A string is nothing but a collection of characters. In very simple terms, String may be
defined as the array of characters. When it comes to an understanding variable, Integer is
the very first thing we learn about. An integer is the data type that stores the integer value,
in the same way, char is the data type that stores single character and similarly, a string is
the data type that allows the storage of the set of characters in a single variable.
Output: 04:10:43 PM
Join This VB.Net String function is used to Input
join two substrings.
Dim ItemList() As String
= {“Apple”, “Banana”,
“Guava”}
Dim JoinItemList as
string = Join(ItemList, ",
")
Output: Hey
Len This String function in VB.Net will Input
return the numbers of characters in a Dim StrWords as String =
string. “You are a hero!”
Dim WordCount as
Integer = Len(StrWords)
Output: 15
Right This function will return the specified Input
number of characters from a string from Dim CheckStr as string =
the right side. “Hey Jim”
Dim ResultStr as string =
Right(CheckStr, 3)
Output: Jim
Output: elppA
Output
HELLO JIM
VB.Net- ARRAY
An array stores a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Types of Array:
1. Fixed size Array:
In this type of array, arraysize is fixed at the beginning. Changin the size is not allowed
later on.
Creating Arrays in VB.Net
To declare an array in VB.Net, you use the Dim statement. For example,
BCA405-GUI Programming: Govt. Zirtiri Residential Science College
Page 9
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", "Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this:
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers
Dim i, j As Integer
' initialize elements of array n
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
2. Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as per the need of
the program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement:
ReDim [Preserve] arrayname(subscripts)
Where, The Preserve keyword helps to preserve the data in an existing array, when you
resize it, arrayname is the name of the array to re-dimension, subscripts specifies the
new dimension.
Module arrayApl
Sub Main()
3. Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called
rectangular
arrays. You can declare a 2-dimensional array of strings as:
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables:
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array:
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
4. Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array
named scores of Integers:
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array:
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
VB.NET COLLECTION
Collection classes are specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes
implement the same interfaces.
The following are the various commonly used classes of the System.Collection
namespace.
Class Description and Usage
ArrayList It represents ordered collection of an object that can be indexed individually.
It is basically an alternative to an array. However, unlike array, you can add
and remove items from a list at a specified position using an index and the
array resizes itself automatically. It also allows dynamic memory allocation,
add, search and sort items in the list.
Hashtable It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you
can identify a useful key value. Each item in the hash table has
a key/value pair. The key is used to access the items in the collection.
SortedList It uses a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of
items that can be accessed using a key or an index. If you access items using
an index, it is an ArrayList, and if you access items using a key, it is a
Hashtable. The collection of items is always sorted by the key value.
Stack It represents a last-in, first out collection of object.
It is used when you need a last-in, first-out access of items. When you add an
item in the list, it is called pushing the item, and when you remove it, it is
called popping the item.
Queue It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an
item in the list, it is called enqueue, and when you remove an item, it is
called deque.
BitArray It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits
in advance. You can access items from the BitArray collection by using
an integer index, which starts from zero.
PROCEDURES
FUNCTIONS
A function is similar to a subroutine or procedure, but a function returns a result. Because
they return values, functions – like variables – have types. The value you pass back to the
calling program from a function is called the return value, and its type determines the type
of the function. Functions accept arguments, just like subroutines. The statements that
make up a function are placed in a set of Function…End function statements, as shown
here:
Function NextDay( ) As Date
Dim thenextDay As date
theNextDay = Now.AddDay(1)
Return theNextDay
End Function
Function are called like subroutines – by name – but their return value is usually assigned
to a variable. To call the NextDay() function, use a statement like this
Dim tomorrow As Date = NextDay()
The Function keyword is followed by the function name and the As keyword that specifies
its type, similar to a variable declaration .The result of a function is returned to the calling
program with the return statement, which is followed by the value you want to return
from your function. This value, which is usually a variable, must be of the same type as the
function. You can also a value to the calling routine by assigning the result to the name of
the function. The following is an alternate method of coding the NextDay() function:
Function Nextday() As Date
NextDay = Now.AddDays(1)
End Function
Similar to the naming of variables, a custom function has a name that must be unique in its
scope( which is also true for subroutines, of course). If you declare a function in a form, the
function name must be unique in form. If you declare a function as Public or Friend, its
name must be unique in the project.
You can call functions in the same way that you call subroutines, but the result won’t be
stored anywhere. For example, the function Convert() might convert the text in a text box
to uppercase and return the number of characters it converted. Normally, you’d call this
function as follows:
nChars = convert()
If you don’t care about the return value – you only want to update the text on a Textbox
control – You would call the convert() function with the following statement:
Convert()
Most of the procedures in an application are functions, not subroutines. The reason is that
a function can return (at the very least) a True/False value that indicates whether it
completed successfully or not.
Example
Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two.
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Recursive Function
A function can call itself. This is known as recursion. Following is an example that
calculates factorial for a given number using a recursive function −
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into
help at these times.
The following example demonstrates this −
Module myparamfunc
Subroutines
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee −
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
In VB.Net, you declare the reference parameters using the ByVal keyword. The following
example demonstrates the concept −
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
In VB.Net, you declare the reference parameters using the ByRef keyword. The following
example demonstrates this −
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
SYNTAX ERRORS
Syntax errors, the easiest type of errors to spot and fix, occur when the code you have
written cannot be understood by the compiler because instructions are incomplete,
supplied in unexpected order, or cannot be processed at all. An example of this would be
declaring a variable of one name and misspelling this name in your code when you set or
query the variable. The development environment in Visual Studio 2010 has a very
When you hover your mouse over the code in error, you’ll receive a ToolTip, telling you
what the error is, and a small gray box with a red circle and a white exclamation point.
EXECUTION ERRORS
Execution errors (or runtime errors) occur while your program is executing. These errors
are often caused because something outside of the application, such as a user, database, or
hard disk, does not behave as expected. In .NET, you will read about error handling or
exception handling. If you talk to a programmer who has not worked in prior languages,
they will use the term exception versus error.
Developers need to anticipate the possibility of execution errors and build appropriate
error-handling logic. Implementing the appropriate error handling does not prevent
execution errors, but it does enable you to handle them by either gracefully shutting down
your application or bypassing the code that failed and giving the user the opportunity to
perform that action again.
One way to prevent execution errors is to anticipate the error before it occurs, and then
use error handling to trap and handle it. You must also thoroughly test your code before
deploying it. Most execution errors can be found while you are testing your code in the
development environment. This enables you to handle the errors and debug your code at
the same time.
LOGIC ERRORS
Logic errors (or semantic errors) lead to unexpected or unwanted results because you did
not fully understand what the code you were writing would do. Probably the most
common logic error is an infinite loop:
Private Sub PerformLoopExample()
HANDLING EXCEPTIONS
VB.Net provides a structured solution to the exception handling problems in the form of
try and catch blocks. Using these blocks the core program statements are separated from
the error-handling statements.
These error handling blocks are implemented using the Try, Catch and
Finally keywords. Following is an example of throwing an exception when dividing by
zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _
is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
A custom exception is being thrown here...
Now inside the Finally Block