Thursday, March 16, 2023

VB .Net Programming Unit-II

                                                     Unit-II: VB.NET chapter 2 

The VB.NET Language- Variables -Declaring variables, Data Type of variables, forcing variables declarations, Scope & lifetime of a variable, Constants, Arrays, types of array, control array, Collections, Subroutines, Functions, passing variable, Number of Argument, Optional Argument, Returning value from function. Control flow statements: conditional statement, loop statement. Msgbox & Inputbox. 

In VB.NET, data type is used to define the type of a variable or function in a program. Furthermore, the conversion of one data type to another type using the data conversion function. 

A Data Type refers to which type of data or value is assigning to a variable or function so that a variable can hold a defined data type value. For example, when we declare a variable, we have to tell the compiler what type of data or value is allocated to different kinds of variables to hold different amounts of space in computer memory. 

Syntax: 

1. Dim Variable_Name as DataType 

VariableName: It defines the name of the variable that you assign to store values. 

DataType: It represents the name of the data type that you assign to a variable. Different Data Types and their allocating spaces in VB.NET 

The following table shows the various data types list in the VB.NET programming language 


Data Types 

Required Space Value Range

Unit-II: VB.NET chapter 2

Boolean 

A Boolean type 

True or False

depends on the 

implementing 

platform 

Byte 

1 byte Byte Range start from 0 to 255 (unsigned)

Char 

2 bytes Char Range start from 0 to 65535 (unsigned)

Date 

8 bytes Date range can be 0:00:0 (midnight) January 1, 0001 to 11:5959 PM of December 31, 

9999.

Decimal 

16 bytes Range from 0 to +/-79,228,162,514,264,337,593,543,950,335 

(+/-7.9…E+28) without any decimal point; 

And 0 to 

+/-7.92281625142264337593543950335 

with 28 position to the right of the decimal

Double 

8 bytes -1.79769313486231570E+308 to -4.94-65645841246544E-324 for negative 

values; 

4.94065645841246544E-324 to 

1.79769313486231570E+308, for positive 

values

Integer 

4 bytes -2,147,483,648 to 2,147,483,647 (signed)



Unit-II: VB.NET chapter 2

Long 

8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (9.2…E + 18) 

(signed)

Object 

Object size based on 

It can store any type of data defined in a 

the platform such as 

variable of type Object

4 bytes in 32-bit and 

8 bytes in 64-bit 

platform 

SByte 

Short 

1 byte -128 to 127 (signed) 

2 bytes -32,768 to 32,767 (signed)

Single 

4 bytes -3.4028235E + 38 to -1.401298E-45 for negative values; 

And for positive value: 1.401298E-45 to 

3.4028235E + 38.

String 

String Datatype 

It accepts Unicode character from 0 to 

depend on the 

approximately 2 billion characters.

implementing 

platform 

UInteger 

4 bytes The range start from 0 to 4,294,967,295 (unsigned)

ULong 

8 bytes The range of ULong start from 0 to 18,446,744,073,709,551,615 (1.8…E + 19) 

(unsigned)



Unit-II: VB.NET chapter 2 

User-Defin ed 

(structure)

A user-defined data 

Each member of the structure has its own 

type depends on the 

data type and limits independent of the other 

implementing 

members' ranges.

platform 

UShort 

2 bytes Range from 0 to 65,535 (unsigned)



Let's use the various data types in a VB.NET program. 

Data_type.vb 

1. Module Data_type 

2. Sub Main() 

3. ' defining the Data Type to the variables 

4. Dim b As Byte =

5. Dim num As Integer =

6. Dim si As Single 

7. Dim db As Double 

8. Dim get_date As Date 

9. Dim c As Char 

10. Dim str As String 

11. 

12. b =

13. num = 20 

14. si = 0.12 

15. db = 2131.787 

16. get_date = Today 

17. c = "A" 

18. str = "Hello Friends..." 

19. 

20. Console.WriteLine("Welcome to the JavaTpoint"

21. Console.WriteLine("Byte is: {0}", b)

Unit-II: VB.NET chapter 2 

22. Console.WriteLine("Integer number is: {0}", num) 

23. Console.WriteLine("Single data type is: {0}", si) 

24. Console.WriteLine("Double data type is: {0}", db) 

25. Console.WriteLine("Today is: {0}", get_date) 

26. Console.WriteLine("Character is: {0}", b) 

27. Console.WriteLine("String message is: {0}", str) 

28. Console.ReadKey() 

29. End Sub 

30.End Module 

Output: 

Welcome to the JavaTpoint 

Byte is: 1 

Integer number is: 20 

Single data type is: 0.12 

Double data type is: 2131.787 

Today is: 31-05-2020 00:00:00 

Character is: 1 

String message is: Hello Friends... 

Type Conversion Functions in VB.NET 

The following functions are available for conversion. 

1. CBool(expression): It is used to convert an expression into a Boolean data type. 

2. CByte(expression): It is used to convert an expression to a Byte data type. 3. CChar(expression): It is used to convert an expression to a Char data type. 4. CDate(expression): It is used to convert an expression to a Date data type. 5. CDbl(expression): It is used to convert an expression into a Double data type. 

6. CDec(expression): It is used to convert an expression into a Decimal data type.

Unit-II: VB.NET chapter 2 

7. CInt(expression): It is used to convert an expression to an Integer data type. 8. CLng(expression): It is used to convert an expression to a Long data type. 9. CObj(expression): It is used to convert an expression to an Object data type. 10.CSByte(expression): It is used to convert an expression to an SByte data type. 11.CShort(expression): It is used to convert an expression to a Short data type. 12.CSng(expression): It is used to convert an expression into a Single data type. 13.CStr(expression): It is used to convert an expression into a String data type. 14.CUInt(expression): It is used to convert an expression to a UInt data type. 15.CULng(expression): It is used to convert an expression to a ULng data type. 

16.CUShort(expression): It is used to convert an expression into a UShort data type. 

In the following, program we have performed different conversion. DB_Conversion.vb 

1. Option Strict On 

2. Module DB_Conversion 

3. Sub Main() 

4. 'defining the Data type conversion 

5. Dim dblData As Double 

6. dblData = 5.78 

7. Dim A, B As Char 

8. Dim bool As Boolean = True 

9. Dim x, Z, B_int As Integer 

10. A = "A" 

11. B = "B" 

12. B_int = AscW(B) 

13. 

14. Console.WriteLine(" Ascii value of B is {0}", B_int) 

15.

Unit-II: VB.NET chapter 2 

16. x =

17. Z = AscW(A) 

18. Z = Z + x 

19. Console.WriteLine("String to integer {0}", Z) 

20. Console.WriteLine("Boolean value is : {0}", CStr(bool)) 

21. Dim num, intData As Integer 

22. 

23. num = CInt(dblData) 

24. intData = CType(dblData, Integer) 

25. Console.WriteLine(" Explicit conversion of Data type " & Str(intData)) 26. Console.WriteLine(" Value of Double is: {0}", dblData) 

27. Console.WriteLine("Double to Integer: {0}", num) 

28. Console.ReadKey() 

29. End Sub 

30.End Module 

Output: 

Ascii value of B is 66 

String to integer 66 

Boolean value is: True 

Explicit conversion of Data type 6 

Value of Double is: 5.78 

Double to Integer: 6 

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.

Unit-II: VB.NET chapter 2 

Creating Arrays in VB.Net 

To declare an array in VB.Net, you use the Dim statement. For example, 

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 − 

Live Demo 

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

Unit-II: VB.NET chapter 2 

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 

Dynamic Arrays 

Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par 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() 

Dim marks() As Integer 

ReDim marks(2) 

marks(0) = 85 

marks(1) = 75 

marks(2) = 90 

ReDim Preserve marks(10)

Unit-II: VB.NET chapter 2 

marks(3) = 80 

marks(4) = 76 

marks(5) = 92 

marks(6) = 99 

marks(7) = 79 

marks(8) = 75 

For i = 0 To 10 

Console.WriteLine(i & vbTab & marks(i)) 

Next i 

Console.ReadKey() 

End Sub 

End Module 

When the above code is compiled and executed, it produces the following result − 

0 85 

1 75 

2 90 

3 80 

4 76 

5 92 

6 99 

7 79 

8 75 

9 0 

10 0 

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 −

Unit-II: VB.NET chapter 2 

Live Demo 

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

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 

a[3,0]: 3 

a[3,1]: 6 

a[4,0]: 4 

a[4,1]: 8 

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 − 

Live Demo 

Module arrayApl 

Sub Main() 

'a jagged array of 5 array of integers

Unit-II: VB.NET chapter 2 

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 

a[3][0]: 3 

a[3][1]: 6 

a[4][0]: 4 

a[4][1]: 8 

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. 

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index, etc. These classes create collections of objects of the Object class, which is the base class for all data types in VB.Net.

Unit-II: VB.NET chapter 2 

Various Collection Classes and Their Usage The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their details.

Class 

Description and Useage

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.



Unit-II: VB.NET chapter 2 

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 

BitArray 

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. 

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.



Subroutines 

The idea of breaking a large application into smaller, more manageable sections is not new to computing. Few tasks, programming or otherwise, can be managed as a whole. The event handlers are just one example of breaking a large application into smaller tasks. 

For example, when you write code for a shoppingmode controls Click event, you concentrate on the event at hand — namely, how the program should react to the Click event. What happens when the shoppingmode control is double-clicked or when

Unit-II: VB.NET chapter 2 

another control is clicked is something you will worry about later — in another control’s event handler. This divide-and-conquer approach isn’t unique to programming events. It permeates the Visual Basic language, and even the longest applications are written by breaking them into small, well-defined, easily managed tasks. Each task is performed by a separate procedure that is written and tested separately from the others. As mentioned earlier, the two types of procedures supported by Visual Basic are subroutines and functions. 

Subroutines usually perform actions and they don’t return any result. Functions, on the other hand, perform some calculations and return a value. This is the only difference between subroutines and functions. Both subroutines and functions can accept arguments, which are values you pass to the procedure when you call it. Usually, the arguments are the values on which the procedure’s code acts. Arguments and the related keywords are discussed in detail in the “VB.NET Arguments” section later in this chapter. 

A subroutine is a block of statements that carries out a well-defined task. The block of statements is placed within a set of Sub. . .End Sub statements and can be invoked by name. 

The following subroutine displays the current date in a message box and can be called by its name, ShowDate(): 

Sub ShowDate() 

MsgBox(Now().ToShortDateString) 

End Sub 

Code language: VB.NET (vbnet) 

Normally, the task performed by a subroutine is more complicated than this; but even this simple subroutine is a block of code isolated from the rest of the application. The statements in a subroutine are executed, and when the End Sub statement is reached, shoppingmode control returns to the calling program. It’s possible to exit a subroutine prematurely by using the Exit Sub statement. 

All variables declared within a subroutine are local to that subroutine. When the subroutine exits, all variables declared in it cease to exist. 

Most procedures also accept and act upon arguments. The ShowDate() subroutine displays the current date in a message box. If you want to display any other date, you have to implement it differently and add an argument to the subroutine: 

Sub ShowDate(ByVal birthDate As Date)

Unit-II: VB.NET chapter 2 

MsgBox(birthDate.ToShortDateString) 

End Sub 

Code language: VB.NET (vbnet) 

birthDate is a variable that holds the date to be displayed; its type is Date. The ByVal keyword means that the subroutine sees a copy of the variable, not the variable itself. What this means practically is that the subroutine can’t change the value of the variable passed by the calling application. To display the current date in a message box, you must call the ShowDate() subroutine as follows from within your program: 

ShowDate() 

Code language: VB.NET (vbnet) 

To display any other date with the second implementation of the subroutine, use a statement like the following: 

Dim myBirthDate = #2/9/1960# 

ShowDate(myBirthDate) 

Code language: VB.NET (vbnet) 

Or, you can pass the value to be displayed directly without the use of an intermediate variable: 

ShowDate(#2/9/1960#) 

Code language: VB.NET (vbnet) 

If you later decide to change the format of the date, there’s only one place in your code you must edit: the statement that displays the date from within the ShowDate() subroutine. 

Visual Basic Programming Fundamentals Functions 

Functions 

A function is similar to a subroutine, 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 must match 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:

Unit-II: VB.NET chapter 2 

Function NextDay() As Date 

Dim theNextDay As Date 

theNextDay = Now.AddDays(1) 

Return theNextDay 

End Function 

Code language: VB.NET (vbnet) 

The Function keyword is followed by the function name and the As keyword that specifies its type, similar to a variable declaration. AddDays is a method of the Date type, and it adds a number of days to a Date value. The NextDay() function returns tomorrow’s date by adding one day to the current date. NextDay() is a custom function, which calls the built-in AddDays method to complete its calculations. 

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. In our example, the Return statement happens to be the last statement in the function, but it could appear anywhere; it could even appear several times in the function’s code. The first time a Return statement is executed, the function terminates, and control is returned to the calling program. 

You can also return 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

Unit-II: VB.NET chapter 2 

Code language: VB.NET (vbnet) 

Notice that this time I’ve assigned the result of the calculation to the function’s name directly and didn’t use a variable. This assignment, however, doesn’t terminate the function like the Return statement. It sets up the function’s return value, but the function will terminate when the End Function statement is reached, or when an Exit Function statement is encountered. 

Similar to 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 the form. If you declare a function as Public or Friend, its name must be unique in the project. Functions have the same scope rules as variables and can be prefixed by many of the same keywords. In effect, you can modify the default scope of a function with the keywords Public, Private, Protected, Friend, and Protected Friend. In addition, functions have types, just like variables, and they’re declared with the As keyword. 

Suppose that the function CountWords() counts the number of words, and the function CountChars() counts the number of characters in a string. The average length of a word could be calculated as follows: 

Dim longString As String, avgLen As Double 

longString = TextBox1.Text 

avgLen = CountChars(longString) / CountWords(longString) Code language: VB.NET (vbnet) 

The first executable statement gets the text of a TextBox control and assigns it to a variable, which is then used as an argument to the two functions.When the third

Unit-II: VB.NET chapter 2 

statement executes, Visual Basic first calls the functions CountChars() and CountWords() with the specified arguments, and then divides the results they return. 

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 converts. Normally, you’d call this function as follows: 

nChars = Convert() 

Code language: VB.NET (vbnet) 

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

Parameters and Arguments 

The terms parameter and argument are often used interchangeably, although they have entirely different meanings. Let us illustrate with an example. Consider the following function, which replicates a string a given number of times:

Unit-II: VB.NET chapter 2 

Function RepeatString(ByVal sInput As String, ByVal iCount As Integer) _ 

As String 

Dim i As Integer 

For i = 1 To iCount 

RepeatString = RepeatString & sInput 

Next 

End Function 

The variables sInput and iCount are the parameters of this function. Note that each parameter has an associated data type. 

Now, when we call this function, we must replace the parameters by variables, constants, or literals, as in: 

s = RepeatString("Donna", 4) 

The items that we use in place of the parameters are called arguments. 

Passing Arguments 

Arguments can be passed to a function in one of two ways: by value or by reference. Incidentally, argument passing is often called parameter passing, although it is the arguments and not the parameters that are being passed. 

The declaration of RepeatString given earlier contains the keyword ByVal in front of each parameter. This specifies that arguments are passed by value to this function. Passing by value means that the actual value of the argument is passed to the function. This is relevant when an argument is a variable. For instance, consider the following code:

Unit-II: VB.NET chapter 2 

Sub Inc(ByVal x As Integer) 

x = x + 1 

End Sub 

Dim iAge As Integer = 20 

Inc(iAge) 

Msgbox(iAge) 

Passing a Variable Number of Arguments 

Here's another valuable technique: You can create procedures that can accept a varying number of arguments. You do that with the ParamArray keyword in the argument list, which makes all the arguments passed at that point in the list and after it part of an array. If you use a ParamArray argument, it must be the last argument in the argument list. Here's an example; in this case, the ShowMessage Sub procedure is able to handle a variable number of arguments: 

Module Module1 

Sub Main() 

End Sub 

Sub ShowMessage(ByVal ParamArray Text() As String) 

. 

. 

. 

End Sub 

End Module 

This means that the Text argument here is really an array of arguments. In this example, we can loop over all the arguments in this array, displaying them like this: 

Module Module1 

Sub Main() 

End Sub 

Sub ShowMessage(ByVal ParamArray Text() As String) 

Dim intLoopIndex As Integer 

For intLoopIndex = 0 To UBound(Text) 

Console.Write(Text(intLoopIndex)) 

Next intLoopIndex 

Console.WriteLine("") 'Skip to the next line 

End Sub

Unit-II: VB.NET chapter 2 

End Module 

Now you can call ShowMessage with different numbers of arguments, as you see in Listing 3.4. 

Listing 3.4 Using Variable Numbers of Arguments (VariableArgs project, Module1.vb) Module Module1 

Sub Main() 

ShowMessage("Hello there!") 

ShowMessage("Hello", " there!") 

Console.WriteLine("Press Enter to continue...") 

Console.ReadLine() 

End Sub 

Sub ShowMessage(ByVal ParamArray Text() As String) 

Dim intLoopIndex As Integer 

For intLoopIndex = 0 To UBound(Text) 

Console.Write(Text(intLoopIndex)) 

Next intLoopIndex 

Console.WriteLine("") 

End Sub 

End Module 

Here's what you see when this code runs: 

Hello there! 

Hello there! 

Press Enter to continue... 

Optional Parameters (Visual Basic) 

● Article 

● 09/15/2021 

● 2 minutes to read 

11 contributors 

Feedback 

You can specify that a procedure parameter is optional and no argument has to be supplied for it when the procedure is called. Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply: 

● Every optional parameter in the procedure definition must specify a default value.

Unit-II: VB.NET chapter 2 

● The default value for an optional parameter must be a constant expression. 

● Every parameter following an optional parameter in the procedure definition must also be optional. 

The following syntax shows a procedure declaration with an optional parameter: VB 

Copy 

Sub name(ByVal parameter1 As datatype1, Optional ByVal parameter2 As datatype2 = defaultvalue) 

Calling Procedures with Optional Parameters 

When you call a procedure with an optional parameter, you can choose whether to supply the argument. If you do not, the procedure uses the default value declared for that parameter. 

When you omit one or more optional arguments in the argument list, you use successive commas to mark their positions. The following example call supplies the first and fourth arguments but not the second or third: 

VB 

Copy 

Sub name(argument 1, , , argument 4

The following example makes several calls to the MsgBox function. MsgBox has one required parameter and two optional parameters. 

The first call to MsgBox supplies all three arguments in the order that MsgBox defines them. The second call supplies only the required argument. The third and fourth calls supply the first and third arguments. The third call does this by position, and the fourth call does it by name. 

VB 

Copy 

MsgBox("Important message", MsgBoxStyle.Critical, "MsgBox Example"

MsgBox("Just display this message."

MsgBox("Test message", , "Title bar text"

MsgBox(Title:="Title bar text", Prompt:="Test message")

Unit-II: VB.NET chapter 2 

Determining Whether an Optional Argument Is Present 

A procedure cannot detect at run time whether a given argument has been omitted or the calling code has explicitly supplied the default value. If you need to make this distinction, you can set an unlikely value as the default. The following procedure defines the optional parameter office, and tests for its default value, QJZ, to see if it has been omitted in the call: 

VB 

Copy 

Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ"

If office = "QJZ" Then 

Debug.WriteLine("office not supplied -- using 

Headquarters"

office = "Headquarters" 

End If 

' Insert code to notify headquarters or specified office. End Sub 

If the optional parameter is a reference type such as a String, you can use Nothing as the default value, provided this is not an expected value for the argument. 

Optional Parameters and Overloading 

Another way to define a procedure with optional parameters is to use overloading. If you have one optional parameter, you can define two overloaded versions of the procedure, one accepting the parameter and one without it. This approach becomes more complicated as the number of optional parameters increases. However, its advantage is that you can be absolutely sure whether the calling program supplied each optional argument. 

How to: Return a Value from a Procedure (Visual Basic) 

● Article 

● 09/15/2021 

● 2 minutes to read 

11 contributors 

Feedback

Unit-II: VB.NET chapter 2 

A Function procedure returns a value to the calling code either by executing a Return statement or by encountering an Exit Function or End Function statement. 

To return a value using the Return statement 

1. Put a Return statement at the point where the procedure's task is completed. 

2. Follow the Return keyword with an expression that yields the value you want to return to the calling code. 

3. You can have more than one Return statement in the same procedure. The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, and returns it to the calling code. 

4. VB 

5. Copy 

Function Hypotenuse(side1 As Double, side2 As Double) As Double 

Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2)) 

End Function 

6. 

7. The following example shows a typical call to hypotenuse, which stores the returned value. 

8. VB 

9. Copy 

Dim testLength, testHypotenuse As Double 

testHypotenuse = Hypotenuse(testLength, 10.7

10. 

To return a value using Exit Function or End Function 

1. In at least one place in the Function procedure, assign a value to the procedure's name. 

2. When you execute an Exit Function or End Function statement, Visual Basic returns the value most recently assigned to the procedure's name.

Unit-II: VB.NET chapter 2 

3. You can have more than one Exit Function statement in the same procedure, and you can mix Return and Exit Function statements in the same procedure. 

4. You can have only one End Function statement in a Function procedure. For more information and an example, see "Return Value" in Function Statement. 

Conditional Statements 

Conditional statements are used to perform different actions for different decisions. 

In VBScript we have four conditional statements: 

If statement - executes a set of code when a condition is true If...Then...Else statement - select one of two sets of lines to execute If...Then...ElseIf statement - select one of many sets of lines to execute 

Select Case statement - select one of many sets of lines to execute 

If...Then...Else 

Use the If...Then...Else statement if you want to 

execute some code if a condition is true 

select one of two blocks of code to execute 

If you want to execute only one statement when a condition is true, you can write the code on one line: 

If i=10 Then response.write("Hello") 

There is no ..Else.. in this syntax. You just tell the code to perform one action if a condition is true (in this case If i=10). 

If you want to execute more than one statement when a condition is true, you must put each statement on separate lines, and end the statement with the keyword "End If": 

If i=10 Then 

response.write("Hello")

Unit-II: VB.NET chapter 2 

i = i+1 

End If 

There is no ..Else.. in the example above either. You just tell the code to perform multiple actions if the condition is true. 

If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must add the "Else" keyword: 

Example 

i=hour(time) 

If i < 10 Then 

response.write("Good morning!") 

Else 

response.write("Have a nice day!") 

End If 

Show Example » 

In the example above, the first block of code will be executed if the condition is true, and the other block will be executed otherwise (if i is greater than 10). 

ADVERTISEMENT 

If...Then...ElseIf 

You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to execute: 

Example

Unit-II: VB.NET chapter 2 

i=hour(time) 

If i = 10 Then 

response.write("Just started...!") 

ElseIf i = 11 Then 

response.write("Hungry!") 

ElseIf i = 12 Then 

response.write("Ah, lunch-time!") 

ElseIf i = 16 Then 

response.write("Time to go home!") 

Else 

response.write("Unknown") 

End If 

Show Example » 

Select Case 

You can also use the "Select Case" statement if you want to select one of many blocks of code to execute: 

Example 

d=weekday(date) 

Select Case d 

Case 1

Unit-II: VB.NET chapter 2 

response.write("Sleepy Sunday") 

Case 2 

response.write("Monday again!") 

Case 3 

response.write("Just Tuesday!") 

Case 4 

response.write("Wednesday!") 

Case 5 

response.write("Thursday...") 

Case 6 

response.write("Finally Friday!") 

Case else 

response.write("Super Saturday!!!!") 

End Select 

Show Example » 

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each Case in the structure. If there is a match, the block of code associated with that Case is executed. 

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Unit-II: VB.NET chapter 2 

Programming languages provide various control structures that allow for more complicated execution paths. 

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − 

VB.Net provides following types of loops to handle looping requirements. Click the following links to check their details.

Loop Type 

Do Loop 

Description 

It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.



Unit-II: VB.NET chapter 2 

For...Next 

It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.

For Each...Next

It repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.

While... End While With... End With 

It executes a series of statements as long as a given condition is True. 

It is not exactly a looping construct. It executes a series of statements that repeatedly refer to a single object or structure.

Nested loops 

You can use one or more loops inside any another While, For or Do loop.



Loop Control Statements 

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. 

VB.Net provides the following control statements. Click the following links to check their details.

Unit-II: VB.NET chapter 2 

Control Statement 

Description

Exit statement 

Terminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case.

Continue statement 

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

GoTo statement 

Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program.



MsgBox and InputBox 

A function in Visual Basic 2012 is similar to a normal procedure but the main purpose of the function is to accept a certain input and return a value which is passed on to the main program to finish the execution. There are two types of functions in Visual Basic 2012, the built-in functions (or internal functions) and the functions created by the programmers. 

The syntax of a function is 

FunctionName (arguments) 

The arguments are values that are passed on to the function.In this lesson, we are going to learn two very basic but useful internal functions of Visual Basic 2012 , i.e. the MsgBox( ) and InputBox ( ) functions. 

MsgBox ( ) Function 

The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows:

Unit-II: VB.NET chapter 2 

yourMsg=MsgBox(Prompt, Style Value, Title) 

The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer to Table 12.1 for types of command button displayed. The Title argument will display the title of the message board. 

Style Value 

Named Constant 

Buttons Displayed

vbOkOnly 

Ok button

vbOkCancel 

Ok and Cancel buttons

vbAbortRetryIgnore 

Abort, Retry and Ignore buttons.

vbYesNoCancel 

Yes, No and Cancel buttons

vbYesNo 

Yes and No buttons

vbRetryCancel 

Retry and Cancel buttons



We can use named constants in place of integers for the second argument to make the programs more readable. In fact, Visual Basic 2012 will automatically shows up a list of named constants where you can select one of them. 

For example: 

yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu") and 

yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu") 

are the same. 

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Table 12.2 shows the values, the corresponding named constant and buttons. 


Value 

Named Constant 

vbOk 

vbCancel 



Button Clicked Ok button 

Cancel button

Unit-II: VB.NET chapter 2 

vbAbort 

vbRetry 

vbIgnore 

vbYes 

vbNo 



Example 12.2 

Abort button Retry button Ignore button Yes button No button 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim testMsg As Integer 

testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message") 

If testMsg = 6 Then 

MessageBox.Show("You have clicked the yes 

button") 

ElseIf testMsg = 7 Then 

MessageBox.Show("You have clicked the NO button") Else 

MessageBox.Show("You have clicked the Cancel button") 

End If 

End Sub 

The first argument, Prompt, will display the message 

12.2 The InputBox( ) Function

Unit-II: VB.NET chapter 2 

An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. In VB2005, you can use the following format: 

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position) 

myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The arguments are explained as follows: 

Prompt - the message displayed normally as a question asked. 

Title - The title of the Input Box. 

default-text - The default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to enter. 

x-position and y-position - the position or tthe coordinates of the input box. 

However, the format won't work in Visual Basic 2012 because InputBox is considered a namespace. So, you need to key in the full reference to the Inputbox namespace, which is 

Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position) 

The parameters remain the same. 

Example 12.3 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim userMsg As String 

userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500, 700) 

If userMsg <> "" Then 

MessageBox.Show(userMsg) 

Else 

MessageBox.Show("No Message") 

End If 

End Sub 

The inputbox will appear as shown in the figure below when you press the command button

Unit-II: VB.NET chapter 2


No comments:

Post a Comment