0% found this document useful (0 votes)
42 views42 pages

Unit 2 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views42 pages

Unit 2 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

SDJ International College, Palsana

Unit – 2 Programming in Visual Basic .NET


2.1 Integrated Development Environment (IDE)
 Visual Studio is an Integrated Development Environment (IDE)
developed by Microsoft to develop GUI (Graphical User Interface), console,
Web applications, web apps, mobile apps, cloud, and web services, etc. With
the help of this IDE, you can create managed code as well as native code.
 It is not a language-specific IDE as you can use this to write code in C#,
C++, VB (Visual Basic), Python, JavaScript, and many more languages. It
provides support for 36 different programming languages. It is available for
Windows as well as for macOS.
 Evolution of Visual Studio: The first version of VS (Visual Studio) was
released in 1997, named as Visual Studio 97 having version number 5.0. The
latest version of Visual Studio is 15.0 which were released on March 7,
2017. It is also termed as Visual Studio 2017.
 The supported .Net Framework Versions in latest Visual Studio is 3.5 to 4.7.
Java was supported in old versions of Visual Studio but in the latest version
doesn‟t provide any support for Java language.
 When we start VS 2010, we get startup screen as shown in fig.

Examine this screen capture for a few moments. We are not yet in the Visual Basic

1
SDJ International College, Palsana

environment; therefore this is the Visual Studio Start Page (note the Start Page
tab). The Menu Bar, as well as the green arrows pointing to the New Project and
Open Project choices, is visible. You can use one of these to figure out which type
of.Net project to work on.
Next, on the Menu Bar, select File New Project menu or select New Project from
the Start page and you should see a window something like:

This is the New Project form (see the title bar). This is where selections for the
type of New
Project will be made. There are several important selections to be made on this
form:
1. Project Templates - this is where the .Net language of choice is selected. For
us, this should always be Visual Basic and Windows.
2. Project Applications - this is where we can select from the standard set of
predefined applications. For us, this should always be a Console Application or a
Windows Forms Application.
3. Name - the name to be given to the VB.Net application. The name should
always be indicative of what the application does, e.g. TaxCalculator (not
WindowsApplication1).
4. Location - the file system location where the application folder and files will

2
SDJ International College, Palsana

reside.
Once you click the OK button in the New Project form, you will launch the Visual
Basic.Net Integrated Development Environment (henceforth referred to as the
IDE) window. It is in this window that most, if not all development will be
coordinated and performed. The startup IDE will look something like the
following:

There are four windows on which to focus in this diagram:


1. Solution Explorer - this window contains a list of all open projects and
files/items associated with the current solution.
2. Form designer - this window is where all controls for a given solution will be
placed and manipulated. A windows application may have one, two or many
windows forms associated with it. Note a console application will have no form
designer window, nor toolbox, since a console application contains no forms.
3. Toolbox - this window is where all VB controls will be retrieved from. In
actuality, you can consider the items in the toolbox as class containers. Retrieving
a control from the toolbox is analogous to instantiating an object from that class.
Thus clicking on the button item (class) in the toolbox will give you a button
object. You can either double click on the control you wish to add to the form, or
you can drag and drop your control.

3
SDJ International College, Palsana

4. Properties - this window is where property values are set for a given control.

2.2 Variables and Data types


Variables:
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in VB.Net has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be stored within
that memory; and the set of operations that can be applied to the variable.

Variable naming conventions:


Variable name follow certain rules:
 First character must be a letter.
 It can contain digits and alphabets.
 No special character allowed except underscore.
 Reserved word cannot be used as variable name.

Example
 Valid variable names temp, emp_name, bookl.
 Invalid variable name: emp&name, emp no, dim.

Variable Declaration
 Dim keyword is used to declare variable.
 Data type of variable is defined by As clause.

Syntax:
{Dim | Public | Private | Friend | Protected Friend | Static} variable name(s) [As
datatype [= expression]]
Examples:
 Dim a As Integer
 Public dtl As Date
 Dim name As String
 Dim x, y As Integer

A user can also initialize variable at the time of declaration as follow:


 Dim x As Integer = 5
 Dim name As String = "visual studio"

4
SDJ International College, Palsana

If variable is not assigned at the time of declaration then the variable has a default
value based on its type. The following are the default values for different types of
variable.
 Dim a As Integer
'declare variable of type Integer and its default value 0.

 Dim dtl As Date
'declare variable of type Date and its default value is 12:00:00 am
 o Dim name As String
'declare variable of type String and its default value is Nothing
 Dim sng| As Single
'declare variable of type single and its default value 0.
 If variable is declared without As clause, then it will be considered as object
type variable.

Examples
 Dim objl
'declare variable of type object (default datatype)

Moreover, user can assign value to the variable as follow:


 a = 5 'assign Integer value
 name = " visual studio" 'assign String value.
 dt1 = #01/01/2013# 'assign Date value.
 sng1 = 5.4 'assign Single value

Data types:
A data types determines the permissible value and what kind of data a variable
hold. We can categorize data types as per kind of its value.

There are four types of data types:


1. Numeric data types
2. Character data types
3. User defined data types
4. Miscellaneous data types

Data Type Storage Allocation Value Range


Boolean Depends on implementing True or False
platform
Byte 1 byte 0 through 255 (unsigned)

5
SDJ International College, Palsana

Char 2 bytes 0 through 65535 (unsigned)


Date 8 bytes 0:00:00 (midnight) on January 1, 0001
through
11:59:59 PM on December 31, 9999
Decimal 16 bytes 0 through +/-
79,228,162,514,264,337,593,543,950,3
35 (+/-
7.9...E+28) with no decimal point; 0
through +/-
7.9228162514264337593543950335
with 28
places to the right of the decimal
Double 8 bytes -1.79769313486231570E+308 through
-
4.94065645841246544E-324, for
negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for
positive values
Integer 4 bytes -2,147,483,648 through 2,147,483,647
(signed)
Long 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807(signed)
Object 4 bytes on 32-bit Any type can be stored in a
platform 8 bytes on 64- variable of type Object
bit platform
SByte 1 byte -128 through 127 (signed)
Short 2 bytes -32,768 through 32,767 (signed)
Single 4 bytes -3.4028235E+38 through -1.401298E-
45 for
negative values;
1.401298E-45 through 3.4028235E+38
for
positive values
String Depends on implementing 0 to approximately 2 billion Unicode
platform characters
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615
(unsigned)
User- Depends on Each member of the structure has a
Defined implementing platform range determined by its data type and
independent of
the ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)

6
SDJ International College, Palsana

Boxing and Unboxing :


Boxing and unboxing is an important concept in VB.NET's type system. With
Boxing and Unboxing one can link between value-types and reference-types by
allowing any value of a value-type to be converted to and from type object.

Boxing
 Boxing is a mechanism in which value type is converted into reference type.
 It is implicit conversion process in which object type (super type) is used.
 In this process type and value both are stored in object type.

Unboxing
 Unboxing is a mechanism in which reference type is converted into value.
 It is explicit conversion process.

Example:
Private Sub btnconversion_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnconversion.Click
Dim i As Integer = 123
Dim obj As Object
obj = i ' boxing ,implicit conversion
Dim J As Integer
J = CInt(obj) 'unboxing ,explicit conversion
MsgBox("Value of i : " & i)
MsgBox(obj)
MsgBox("Value of j :" & J)
End Sub

7
SDJ International College, Palsana

2.2.2. Enumerations
Enum is a keyword known as Enumeration. Enumeration is a user-defined data
type used to define a related set of constants as a list using the keyword enum
statement. It can be used with module, structure, class, and procedure. For
example, month names can be grouped using Enumeration.
Syntax:
Enum enumerationname [ As datatype ]
memberlist
End Enum

Example:

Public Class Frmenum


Enum Temperature
Low
Medium
High
End Enum
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim value As Temperature = Temperature.Medium
If value = Temperature.Medium Then
MsgBox("Temperature is Mediuam..")
End If
End Sub
End Class

Comments:
 A comment in the source code is used to make it more understandable. They
serve as inline documentation that helps to read, reuse, understand and
maintain existing code.
 There are two ways to comment in VB.NET:
1. „ (Single Quote)
2. REM (Remark Statement)

Scope:
Visibility Modes / Access Modifiers /Access Specifies
 Private: It is accessible in the module, class or structure in which they are

8
SDJ International College, Palsana

declared.
 Public: It is accessible in all procedures of all classes, modules and
structures in application
 Static: Retains their values within the scope of the method in which they are
declared.
 Protected: It is accessible in the class in which they are declared or derived
class
 Friend: It is accessible in any class or module within the assembly.
 Shared: Shared members such as properties, procedures or fields that are
shared by all instances of a class.
 Both Dim and private are considered as private modifier.

Constants:
 Constant is an entity whose value never changes during program execution.
 Const keyword is used to declare a constant. Constants must be initialized at
the time of declaration.

Syntax:
[Public | Private | Friend | Protected | Friend}]
Const constant name [As datatype] = expression

Examples
 Const pi As Single = 3.14
 Const Val = 500 'declared constant of type object

2.2.3. Data Type Conversion Functions


Type conversion is used for convert one data type to another. There are types of
conversion:
1. Implicit conversion: conversion is done automatically by the compiler is
called implicit conversion. It will automatically convert smaller data types
to large data types. It is also called narrowing to widening (small to
large) conversion.
2. Explicit conversion: The compiler does not convert a type to another type
automatically. This type of conversion is called explicit conversion. A type
conversion keyword is used when performing an explicit conversion. It is
also called widening to narrowing conversion (larger to small).

9
SDJ International College, Palsana

Example:
Private Sub btnimex_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnimex.Click
Dim num1 As Integer = 100
Dim num2 As Integer = 75
Dim total As Long
'implicit conversion
total = num1 + num2
MsgBox("Total is : " & total)
An explicite conversion requires function
Dim num As Integer
Dim marks As Decimal = 34.75
'In this the Decimal values are explicitly converted to Integer data type
with rounding the marks 35
'you have to tell compiler to do the conversion, it uses casting
num = CInt(marks)
MsgBox("Converted value is: " & num)

CType Function: It uses to convert one type to another type. Instead of remember
all conversion functions, remember only CType function.

Syntax:

CType(expression, typename)

where,
Expression: any valid expression
Type name: the name of any data type, objects, structure, class, or interface.
Dim text
Example:
Dim text As String = "25.56"
Dim perd As Double
Dim perI As Integer
perd = CType(text, Double) + 1.14
perI = CType(text, Integer)
MsgBox("The value of percentage is: " & perd)
MsgBox("The value of percentage is: " & perI)

10
SDJ International College, Palsana

Type Checking Function


Vb.net provides number of data verification or data type checking function as
below. It returns Boolean value (true/false).
1. IsDate
2. IsNothing
3. IsNumeric
4. IsDBNull
5. IsArray
1. IsDate: It returns true or false

Exmaple:

Private Sub btnisdate_Click(ByVal sender AsSystem.Object, ByVal e


AsSystem.EventArgs) Handlesbtnisdate.Click
'IsDate returns true or false
Dim dt1 As Date
Dim strtmep As String
Dim bolans As Boolean
dt1 = Now.ToShortDateString
bolans = IsDate(dt1)
MsgBox(bolans) 'True
strtmep = "testing"
bolans = IsDate(strtmep)
MsgBox(bolans) 'false
EndSub

2. IsNothing: Returns true if the object variable that currently has no assigned
value otherwise, it returns false.

Example:
Private Sub btnisnothing_Click(ByVal sender AsSystem.Object, ByVal e AsSystem.EventArgs) Handles
btnisnothing.Click
'Returns True if the object variable that currently has no assigned vale otherwise
,itreturs false
Dim objtemp As Object
Dim objans As Boolean
objans = IsNothing(objtemp)
MsgBox(objans) 'True
objtemp = "testing"
objans = IsNothing(objtemp)
MsgBox(objans) 'False
EndSub

11
SDJ International College, Palsana

3. IsNumeric: Returns True of the value is numeric, otherwise it returns False.

Example:

Private Sub btnnumeric_Click(ByVal sender AsSystem.Object, ByVal e


AsSystem.EventArgs) Handlesbtnnumeric.Click
'Returns True of the value is numeric ,otherwise it returns False
Dim objtemp As Object
Dim objans As Boolean
objtemp = 53
objans = IsNumeric(objtemp)
MsgBox(objans)
objtemp = "Rs.53"
objans = IsNumeric(objtemp)
MsgBox(objans)
EndSub

4. IsDBNull: It returns true if the value evaluates to the DBnulltype, otherwise it


returns False.
Example:
Private Sub btnDBnull_Click(ByVal sender AsSystem.Object, ByVal e AsSystem.EventArgs)
HandlesbtnDBnull.Click
'IsDBNull returns True if the value evalutes to the DBnulltype,otherwise retuns
False
Dim objtemp As Object
Dim objans As Boolean
objans = IsDBNull(objtemp)
MsgBox(objans)
objtemp = System.DBNull.Value
objans = IsDBNull(objtemp)
MsgBox(objans)
EndSub

12
SDJ International College, Palsana

5. IsArray: Returns True of the value is array, otherwise it returns False.

Example:

Private Sub btnisarray_Click(ByVal sender AsSystem.Object, ByVal e


AsSystem.EventArgs) Handlesbtnisarray.Click
'Returns True of the value is array ,otherwise it returs False
Dim ary() As Integer = {1, 2}
Dim objtemp As Object
objtemp = ary
MsgBox(IsArray(objtemp)) „True
EndSub

2.2.4. Statements/ option statements /Compile option


There are four option statements available in Vb.Net:
1. Option Explicit: It has two modes: 1. on (by default) 2. Off
If program has 'Option explicit on' statement than it requires all variables have
proper declaration otherwise it gives compile time error. If we use 'Option
explicit off' statement than vb.net create variable declaration automatically
and program does not give an error.

Example:
Option Explicit On
Private Sub btnExplicit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnExplicit.Click
Dim ans As Integer
ans = 5
End Sub

Option Explicit Off


Private Sub btnExplicit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnExplicit.Click
'Dim ans As Integer
ans = 5
End Sub

Note: Above program run continue without error.


Note: For better coding it is recommended to declare variables with Dim keyword
and data type.

13
SDJ International College, Palsana

2. Option Compare: It has two modes:


1. Binary (by Default)
2. Text
We can change string comparison method by set the text or Binary.

Example:
Private Sub btncompare_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btncompare.Click
If "Hello" = "HELLO" Then
MessageBox.Show("True")
Else
MessageBox.Show("False")
End If
End Sub

In above program, if we use Option Compare Binary, messagebox show 'false' and
if we use 'Text' mode than messagebox show 'True. That means when we set
Option Compare to Text we can able compare string with Case insensitive
comparison.

3. Option Strict: Option Strict is prevents program from automatic variable


conversions that is implicit data type conversions. It will check strictly Type
Checking. While converting one data type to another if there is data loss then it
will show a compile time error (Narrowing conversion). It has also two modes:
1. On
2. Off (by default)
Example:
Private Sub btnstrict_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnstrict.Click
Dim no1 As Double
Dim no2 As Integer
no1 = 9.123
MsgBox(no1)
no2 = no1
MsgBox(no2)
End Sub

14
SDJ International College, Palsana

The above program is a normal vb.net program and is in default Option Strict Off
mode so we can convert the value of Double to an Integer.
4. Option Infer: The
Infer option indicates whether the compiler should determine the
type of a variable from its value. It has also two modes:
1. On (by default)
2. Off
Example:
Private Sub btninfer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btninfer.Click
Dim a = 25 'it is considered as integer
Dim b = "Hello" ' it is considered as string
End Sub

Example:
Option infer on.
Dim a=25
Take the mouse over variable a.
a‟s data type is integer(see in tooltip).

Option infer off.


Dim a=25
Take the mouse over variable a.
a‟s data type is object (see in tooltip).

2.3. String & Date Functions and Methods

2.3.1 String Function:


1. Len: Returns an integer that contains the number of characters in a string.
Syntax: Len (string)
2. Mid: Returns a string containing a specified number of characters from a
string.
Syntax: Mid (string, start [, length])
String - String expression from which characters are returned.
Start - Long. Character position in string at which the part to be taken
begins.
Length - Length is Optional. Number of characters to return.
3. Left: Returns a string containing a specified number of characters from the

15
SDJ International College, Palsana

left side of a String.


Syntax: Left ("string", n)
4. Right: Returns a string containing a specified number of characters from the
right side of string.
Syntax: Right ("string", n)
5. Space: Returns a string consisting of the specified number of spaces.
Syntax: Space (number)
6. Replace: Returns a string in which a specified substring has been replaced
with another substring.
Syntax: Replace (string, searchtext, replacetext)
7. Trim: Returns a string containing a copy of a specified string with no leading
or trailing spaces.
Syntax: Trim ("String")
8. Ltrim: Returns a string containing a copy of a specified string with no
leading spaces.
Syntax:Ltrim("string")
9. Rtrim: Returns a string containing a copy of a specified string with no
trailing spaces.
Syntax: Rtrim ("string")
10.Ucase: Returns a string or character containing the specified string converted
to uppercase.
Syntax: Ucase ("string")
11.Lcase: Returns a string or character converted to lowercase.
Syntax: LCase("string")
12.InStr: Returns an integer specifying the start position of the first occurrence
of one string within another.
Syntax: Instr (n, original Text, embedded Text)

16
SDJ International College, Palsana

Example - This example defines all the string function.

Private Sub btnstringfun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnstringfun.Click
'Len Function
Dim leng As Integer= Len("Visual Basic")
MessageBox.Show("length is :" & leng)
'Mid Function
Dim middle As String = Mid("Visual Basic", 3, 4)
MessageBox.Show("Mid is :" & middle)
'Replace Function
Dim replaces As String = Replace("Visual Basic", "Basic", "Advance")
MessageBox.Show("Replace is :" & replaces)
'Trim Function
Dim trimt As String = Trim(" Visual Basic ")
MessageBox.Show("Trim is :" & trimt)
'Ltrim Function
Dim ltriml As String = LTrim(" Visual Basic ")
MessageBox.Show("Ltrim is :" & ltriml)
'Rtrim Function
Dim rtrimr As String = RTrim(" Visual Basic ")
MessageBox.Show("Rtrim is :" & rtrimr)
'Ucase Function
Dim ucaseu As String = UCase("Visual Basic")
MessageBox.Show("Ucase is :" & ucaseu)
'Lcase Function
Dim lcasel As String = LCase("VISUAL CASE")
MessageBox.Show("Lcase is :" & lcasel)
'Instr Function
MsgBox(InStr(1, "Visual Basic", "Basic"))
End Sub

2.3.2 Math Function:


1. Abs: Returns the absolute value of a number.
Syntax: Abs(n)
2. Max: Returns the larger of two numbers.
Syntax: Max(n1,n2)
3. Min: Returns the smaller of two numbers.
Syntax: Min(n1,n2)
4. Pow: Returns a specified number raised to the specified power.
Syntax: Pow(n1,n2)
Here, n1 is the number and n2 is the power of the number.

17
SDJ International College, Palsana

5. Sqrt: Returns the square root of a specified number.


Syntax: Sqrt(n1)
6. Ceiling: Returns the smallest integral value that's greater than or equal to the
specified Decimal or Double.
Syntax: Ceiling(n)
7. Floor: Returns the largest integer that's less than or equal to the specified
Decimal or Double number.
Syntax: Floor(n)

Example:
Private Sub btnmath_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnmath.Click
Dim absolute As Integer
absolute = Abs(-16)
MessageBox.Show("The absolute value is: " & absolute)
Dim minimum As Integer
minimum = Min(18, 12)
MessageBox.Show("The minimum value is: " & minimum)
Dim maximum As Integer
maximum = Max(18, 12)
MessageBox.Show("The maximum value is: " & maximum)
Dim square As Integer
square = Sqrt(9)
MessageBox.Show("The square root is: " & square)
Dim power As Integer
power = Pow(2, 3)
MessageBox.Show("The power is: " & power)
End Sub

2.3.3 Date Function:


1. DateSerial: It returns a Date value representing a specified Year, Month, and
Day.
Syntax: DateSerial(Year,Month,Day)
2. Year:It will extract Year part from any Date.It returns only integer value.
Syntax: Year(Date)
3. Month:It will extract Month part such as 1,2,3,4 and so on from any Date. It
returns only integer value.
Syntax: Month(Date)
4. MonthName: It will show Month Name as January,February and so on from

18
SDJ International College, Palsana

any Date. It returns only string value.


Syntax: MonthName(Month)
5. Day:It will display Day in number. It returns only integer value. Actually it's
an Enum which as Sunday,Monay and so on. It specifies the day of the week.
Syntax: Day(Date)
6. DateDiff: The DateDiff function returns the number of intervals between two
dates.
Syntax: DateDiff(interval,date1,date2)
The interval you want to use to calculate the differences between date1 and
date2 can take the following interval values:

yyyy Year
q Quater
m Month
y Day of Year
d Day
w Week Day
ww Week of Year
h Hour
n Minute
s Second

7. FormatDateTime: Display a date in different formats:


Syntax:FormatDateTime(date,format)
A value that specifies the date/time format to use. You can take the following
values:

0 = vbGeneralDate– Default Returns date: mm/dd/yyyy and time if specified:


hh:mm:ss PM/AM.
1 = vbLongDate Returns date: weekday, monthname, year
2 = vbShortDate Returns date: mm/dd/yyyy
3 = vbLongTime Returns time: hh:mm:ss PM/AM
4 = vbShortTime Return time: hh:mm

2.3.4 Methods:
In visual basic, Method is a separate code block and that will contain a series of
statements to perform particular operations. Generally In visual basic Methods
are useful to improve the code reusability by reducing the code duplication.

19
SDJ International College, Palsana

Suppose. If we have the same functionally to perform in multiple places, then we


can create one method with the required functionality and use it wherever it is
required in the application.
In visual basic, we can create the Methods either by using Sub or Function
keywords like as shown below. If we create a method with Sub keyword that
will not allow us to return any value. In case, if you want to return any value,
then you need to use Function keyword to create the method.
Syntax of Visual Basic Methods

<Access Specifier> Sub Method_Name([<Parameters>])


Statements to Execute
End Sub
OR
<Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>
Statements to Execute
Return return val
End Function

Parameter Description
Access_Specifier It is useful to define an access level either public or private
etc. to allow other classes to access the method. If we didn‟t
mention any access modifier. Then by default it is private.
Method_Name It must be a unique name to identify the method.
Parameters The method parameters are useful to send or receive data
from a method and these are enclosed within parentheses and
are Separated by commas. In case. If no parameters are
required for a method then. We need to define a method with
empty Parentheses.
Return_Type It is useful to specify the type of value the method can return

2.4. Modules, Procedures and Functions


Module: Modules are containers to define custom functions, procedures or
variables to group code in Visual Basic. Module containing an entry point
subroutine (main) is an entry module. It is always at least one module defined in
the Visual Basic macro.

20
SDJ International College, Palsana

Concept of Procedure:
 Procedures are made up of series of statements.
 It can be called when required and it can be executed.
 After the execution of the procedure is completed, the execution continues
from the statement that called the procedure.
 You can pass data to procedures and the code in the procedure can work on
that data.
 Each procedure can handle one and only one task.
 There are two types of procedure in vb.NET.
1. Sub routine
2. Functions

Sub routine: Sub procedures are procedures that do not return any value.

Syntax
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
 Modifiers: specify the access level of the procedure; possible values
are: Public, Private,Protected, Friend, Protected Friend and
information regarding overloading, overriding, sharing, and
shadowing.
 SubName: indicates the name of the Sub.
 ParameterList: specifies the list of the parameters.

Example
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Messagebox.Show("Total Pay”: ,pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)

21
SDJ International College, Palsana

End Sub
End Module

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this
mechanism, when a method is called, a new storage location is created for each
value parameter. The values of the actual parameters are copied into them. So, the
changes made to the parameter inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword.
Example:

Sub swapbyval(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
Private Sub btnbyval_Click(…) Handles btnbyval.Click
MsgBox("before swap")
MessageBox.Show(txtno2.Text)
MessageBox.Show(txtno3.Text)
swapbyval(txtno2.Text, txtno3.Text)
MsgBox("after swap")
MessageBox.Show(txtno2.Text)
MessageBox.Show(txtno3.Text)
End Sub

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you
pass parameters by reference, unlike value parameters, a new storage location is
not created for these parameters. The reference parameters represent the same
memory location as the actual parameters that are supplied to the method. In
VB.Net, you declare the reference parameters using the ByRef keyword.

22
SDJ International College, Palsana

Example:

Sub swapbyref(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
Private Sub btnref_Click(…) Handles btnref.Click
MsgBox("before swap")
MessageBox.Show(txtno2.Text)
MessageBox.Show(txtno3.Text)
swapbyref(txtno2.Text, txtno3.Text)
MsgBox("after swap")
MessageBox.Show(txtno2.Text)
MessageBox.Show(txtno3.Text)
End Sub

Functions: Functions return a value.

Syntax:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function

Where,
 Modifiers: specify the access level of the function; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
 FunctionName: indicates the name of the function.
 ParameterList: specifies the list of the parameters
 ReturnType: specifies the data type of the variable the function returns

Example:
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2

23
SDJ International College, Palsana

End If
FindMax = result
End Function

Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways:
 By using the return statement
 By assigning the value to the function name

2.4.2. Optional arguments


The optional parameter contains a default value with Optional keyword. If we will
not pass the value for optional parameters then it will use the default value. If we
pass the values then it will override value.

Example:

Function AddNum(ByVal num1 As Integer, Optional ByVal num2 As Integer = 20, Optional
ByVal num3 As Integer = 30) As Integer
Return num1 + num2 + num3
End Function
Private Sub btnoptionalarg_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnoptionalarg.Click
Dim result As Integer = 0
result = AddNum(10)
MsgBox("Addition is: {0}" & result)
result = AddNum(10, 40)
MsgBox("Addition is: {0}" & result)
result = AddNum(10, 40, 60)
MsgBox("Addition is: {0}" & result)
End Sub

Breaking lines:
A user can write single statement into multiple lines using the (underscore)
character at end of a statement.
Example
 Dim name As String
name = "visual studio"
You can Break the statement as follows:
name = "visual" &_
"studio"

24
SDJ International College, Palsana

Joining lines:
A user can joint multiple lines / statements using: (colon) character.

Example
Dim X, Y As Integer
X=10
Y=20
X=10: Y=20

Arrays:
 It stores a fixed size sequential collection of elements of the same type.
 It is used to store a collection of data.
 It consists of contiguous memory locations.
 The lowest element corresponds to the first and the highest element to the
last.
 It provides best performance for certain requirements.
 The elements in an array can be stored and accessed by using the index of the
array.
To declare an array in VB.Net, you use the Dim statement

Example:
(1) Dim intData(10) As Integer ' an array of 11 elements
(2) Dim strData(20) As String ' an array of 21 strings
(3) Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
(4) Dim ranges(10, 100) 'a two dimensional array.
You can also initialize the array elements while declaring the array.
Example:
(1) Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
(2) Dim names() As String = {"Karthik", "Sandhya", "Shivangi", "Ashwitha",
"Somnath"}
(3) Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}

25
SDJ International College, Palsana

Example:

Private Sub btnarry_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnarry.Click
lstarr.Items.Clear()
Dim num(3) As Integer
num(0) = 10
num(1) = 20
num(2) = 30
For i = 0 To 2
lstarr.Items.Add(num(i))
Next
End Sub

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:
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. Subscript specifies the
new dimension.

26
SDJ International College, Palsana

Example:
Private Sub btndyarray_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btndyarray.Click
lstarr.Items.Clear()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
MsgBox(marks.Length)
'ReDim marks(10)
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
MsgBox(marks.Length)
For i = 0 To 10
lstarr.Items.Add(i & vbTab & marks(i))
Next i
End Sub

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
3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer.
Collections:
 A collection can also store group of objects. But unlike an array which is of
fixed length, the collection can grow or shrink dynamically.
 Items can be added or removed at run time.
 These are the specialized classes for data storage and retrieval.
 It supports stack, queues, lists and hash tables.

27
SDJ International College, Palsana

Collection includes various classes are as follows:

Class Description
ArrayList It represents ordered collection of an object that can be indexed
individually.
Hashtable It uses a key to access the elements in the collection.
SortedList It uses a key as well as an index to access the items in a list.
Stack It represents LIFO(Last-In-First-Out) collection of object.
Queue It represents FIFO(First-In-First-Out) collection of object.

Control Flow Statements / Conditional Statements :


 Also known as Branching statements.
 A branch is a point at which your program must make a choice.
 A branch statement, or conditional statement. is a code that allows you to
test whether statements are true or false and then execute some code based
on comparisons.

If... Then... Elself Statement:


 The If…Then….Elself statement is the conditional statements.
 It is also called branch.
 When the program arrives at If statement during its execution, control will
"branch" off into one of two or more "directions".

28
SDJ International College, Palsana

Syntax:
If condition | Then
[statement(s)]
[Elself condition2 Then
[statement(s)]
.
.
[Else
[statement(s)]]
End If

Select... Case Statement


 Used to avoid long chains of If... Then... Elself statement.
 Often, it is necessary to compare one specific variable against several
constant expressions then we use select...case statement.
 Syntax:
Select Case testexpression
Case expression I
[statement(s)
.
.
[Case Else
[statement(s)]]
End Select

29
SDJ International College, Palsana

Loop Statements:

Looping :
 Looping allows user to run one or more lines of code repetitively.
 You can repeat the statements in a loop until a condition is True.
 Once a condition is False execution of those statements stops.
 VB.NET supports while, do, for and for-each loops.

30
SDJ International College, Palsana

While Loop:
While Loop runs set of statements as long as the condition specified with While
loop is True.
Syntax
While condition
[statement(s)]
End While
Example
Dim intCounter As Integer = 0
Dim intNumber As Integer = 10
While intNumber > 6
intNumber -= 1
intCounter += I
End While

Do Loop:
 Do Loop allows you to test a condition at either the beginning or at the end
of a loop.
 You can also specify whether to repeat the loop while the condition remains
True or False.
 There are two variations of Do loop:
 entry-control loop
 exit-control loop.
Syntax
Do [While | Until) condition] 'condition checked at the beginning of loop
[statements]
[Exit Do]
[statements]
Loop
 Do While.. loop will execute as long as condition is True and Do Until...
loop will execute as long as condition is False.
 These are an entry-control loop.

 The Do... Loop While repetition structure behaves like the While repetition
structure.
 This is an exit-control loop.

31
SDJ International College, Palsana

 Exit Do statement transfers the control to the next statement after the Do
loop.

Syntax
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]

Example
Dim num As Integer = 2
Do While num <= 1000
num = num * 2
Loop
Dim num As Integer = I
Do
num = num * 2
Loop While num <= 1000

For Loop:
 The For... Next loop iterates for a pre-define number of times.
 It uses a loop control variable, also called a counter, to keep track of the
iteration.
 You need to specify the starting and ending values for this counter, and you
can optionally specify the amount by which it increases from one iteration to
another.

Syntax
For index [As Data Type]= start To end
[Step step]
[statement(s)]
[Exit For]
[statement(s)]
Next [index]

Example
For inlndex As Integer = 0 To 3 „Display or calculate
Next intlndex
For inIndex As Integer = 0 To 3 Step 2 ‟Display or calculate
32
SDJ International College, Palsana

Next intindex

For each Loop


 For... Each loop is use to traverse Arrays and Collections.

Syntax:
For each element in group
Logic
Next

Example:
Private Sub btnforeachnext_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnforeachnext.Click
Dim arr(2), temp As Integerarr(0) = 10
arr(1) = 20
arr(2) = 30
For Each temp In arr
MsgBox(temp)
Next
End Sub

With…End with
 It executes a series of statements making repeated reference to a single
object.
 To make this type of code more efficient and easier to read, we use this
block.
 The uses of it do not require calling again and again the name of the object
Set multiple properties and methods quickly.

Syntax:
With object Name
Logic
End with

Example:
Private Sub FrmControlStru_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
With btnsave
.Text = "update"
.ForeColor = Color.Red
33
SDJ International College, Palsana

.BackColor = Color.Black
End With
End Sub

Operators:
Concatenation operators:
 „+‟ and „&‟ are the concatenation operators supported by VB.NET.
 + Operator is used to concatenate values of string datatype.

Example
Dim a As String
a = "Hello" + "World"
Value in a will be “HelloWorld” .
& operator is used to concatenate values of any data type.

Example
Dim Val As String
Val = " NET" & 4.5
Value of Val variable will be .NET 4.5

Arithmetic Operators:
They are used to perform mathematical operations such as addition, subtraction,
multiplication, and division etc on the given numbers.

Syntax
expression = expression I <operator> expression2

Example
x = y + z 'the sum of variables y and z is assigned to variable x.

34
SDJ International College, Palsana

Assignment Operators:
 Assignment operators are used to assign values to variables.
 But along with the standard assignment operator (=), many other operators
can be turned into assignment operator by simply appending an equals sign
to the right of the operator.

Syntax
Variable_name <operator>= expression

Where <operator> is the operator being promoted to an assignment operator.


It is equivalent to following statement.
Variable_name = variable_ name <operator> expression

Example
Dim num As Integer
num = 0
num += 500
num -= 50
num *=2
num /= 50
Relational Operators
 Relational operators are used for comparison in conditional statements.
 So they are used to compare two values and then return a Boolean (i.e., true
or false).
 The greater-than operator (>), for example, returns true if the value on the
left of the operator is greater than the value on its right.

35
SDJ International College, Palsana

Logical and Short-Circuit Operators:


When user need to test whether a condition is true or false, also want to test
whether two conditions are true, or only one is true, or neither is True then logical
operators are used.

 AndAlso - with this operator, if the first operand is False, the second
operand is not tested.
 OrElse - with this operator, if the first operand is True, the second is not
tested.

MessageBox
 It displays a dialog box.
 It interrupts the user that means it immediately blocks further interaction.
 It requires only one Function call.
 We specify buttons, default buttons, an icon, and some other properties of
the dialog.
 It is in System. Windows.Forms namespace.

36
SDJ International College, Palsana

Syntax:
MessageBox.Show (Text[, Caption, Buttons, Icons, Default Button, Options,
HelpFilePath]) As System. Windows.Forms.DialogResult

 Here, the Text is a String displayed in the Message Box,


 Caption is the Text displayed in Title bar of the Message Box,
 Buttons specifies which buttons are to be displayed,
 Icon specifies the picture that will be displayed in the Message Box along
with Text,
 Default Button specifies the default button to be displayed on message box,
 Options specifies display and association options that will be used for the
messagebox,
 HelpFilePath specifies the path and name of the Help file to be display when
the user clicks the Help button.

Example:
MessageBox.Show("Is Visual Basic awesome?", "The Question",_
MessageBoxButtons. YesNoCancel, MessageBoxlcon. Question,_
MessageBoxDefaultButton.Button2)

37
SDJ International College, Palsana

InputBox
 This function accepts value from the user.
 It returns the value entered by the user.

Syntax:
Var=InputBox(sPrompt[, s Title][ ,sDefaultValue][,nX][,nY])
 Here, sPrompt is the prompt to be displayed to the user. It can hold a
maximum of 1024 characters.
 sTitle is the text to be displayed in the title bar of the Input Box. If you skip
it, name of the application is displayed in the title bar.
 DefaultValue is the value displayed in the text box as a default value. If you
omit it, an empty text box is displayed.
 nX is the horizontal distance between the left edge of the inputbox and the
left of the screen. If you omit it, the inputbox is displayed in the horizontal
center of the screen.
 nY is the vertical distance between the top edge of the dialogbox and the top
of the screen.
 If you skip any of the arguments enclosed within square bracket, you need to
retain the corresponding comma delimiter.

Example:
Dim str As String
str = InputBox("Enter your name:", "Name", "Your Name", 100, 100)
Dim res As DialogResult
res = MessageBox.Show(str, "Your Name",_ MessageBoxButtons.OKCancel ,
MessageBoxIcon.Information)
If res = Windows.Forms.DialogResult.OK Then
MessageBox.Show(str)
Else
MessageBox.Show("no value")
End If

Working with events

38
SDJ International College, Palsana

Private Sub btn Welcome_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnWelcome.Click
MessageBox.Show("Welcome, to the World of VB.NET", "Welcome")
End Sub

Sender As System.Object
 It contains the reference of the control or object through which the event was
raised.
 In this example, it contains the reference of Button control.
 It is more useful, if you want to instantiate then use it.
e As System.EventArgs
 It contains information which is needed to process the event.
 The information available depends on the type of events that was raised.
 Since the members available through "e" depends on the kind of action that
raised the event.
Handles
 Handles clause allows the same subroutine to be used for all kinds of event
calls.
 It is used at the end of a procedure declaration to cause it to handle events
raised by an object or controls.

Keyboard Events
 Keyboard events help to respond to specific keystroke as user types it.
 Window passes special keyboard events to our application, so they can
handle the keyboard's input.
 It is also used to handle keyboard events for forms and many controls. These
events are:
 Key Down
 Key Press
 Key Up
 These events respond to combination of keystrokes such as Alt + x, Shift +
p, as well as individual keys.
 After your application receive keyboard input, application can then modify
input or ignore the pressed key, if it is not an expected keystroke.
 Keystroke testing is useful for validating input, playing some type of game,
splash screen closing, etc.

KeyDown Event

39
SDJ International College, Palsana

 Key Down event is generated when a key is pressed.


 Key Down and Key Up events don't report ASCII value of character, but
report its keycode.
 Keycode is a special number that distinguishes each key on keyboard i.e.
exact physical state.
 The key code is unique for each key, not each character.
 Lower-case and Upper-case characters have same key-code, because they
are on same key.
 Number I and ! Symbols have same keycode because same key on keyboard
generate both character.
 Keycodes for letter keys are same as the ASCII code of uppercase character
of letter.
 It also report state of shift, ctrl and alt.

Keyboard Events(Up and Down)

Properties Description
Alt It holds a value indicating whether the Alt key was pressed
or not.
Control It holds a value indicating whether the Ctrl key was
pressed or not.
Handled It holds a value indicating whether the event was handled
or not.
KeyCode It holds the keyboard code for Key Down and KeyUp
Event.
Key Data It holds the keyboard data for Key Down and KeyUp
Event.
KeyValue It holds the keyboard value for KeyDown and
Modifiers It holds the modifier flag for KeyDown and KeyUp event.
This indicates which modifier keys (Ctrl, Shift, and / or
Alt) were pressed These values can be read together using
the control, shift and Alt properties.
Shift It holds a value indicating whether the Shift key was
pressed or not.
SuppressKeyPress It suppresses the events like KeyPress and eyPress KeyUp.

KeyPress Event
 Keypress event occurs every time when user presses:

40
SDJ International College, Palsana

 Uppercase / lowercase letters


 Numeric digit (0-9)
 Punctuation
 enter, tab, backspace
 KeyPress report character that was pressed.
 KeyPress event occurs as soon as users presses key & before control gets
keystroke.

KeyUp Event
 It is generated when key is released.
 It also report state of shift, ctrl and alt.

Mouse Events
 Mouse events occur by the actions of the mouse in a windows form, such as
mouse move and mouse click.
 Window sends mouse events to the program when user works with mouse
while running our application.
 Vb.Net also monitors mouse events when user drags and drops an item on
the screen.
 Following are the different mouse event:

Events Description
MouseDown It occurs when a mouse button is pressed.
MouseEnter It occurs when the mouse pointer enters the control.
MouseHover It occurs when the mouse pointer hovers over the control.
MouseLeave It occurs when the mouse pointer leaves the control.
MouseMove It occurs when the mouse pointer moves over the control.
MouseUp It occurs when the mouse pointer is over the control and the
mouse button is released.
MouseWheel It occurs when the mouse wheel moves and the control has focus.

The event handlers of the mouse events get an argument of type


MouseEventArgs. The MouseEventArgs object is used for handling mouse
events. It has the following properties –

MouseEventsArgs Description
Buttons It indicates the mouse button pressed
Clicks It indicates the number of clicks
Delta It indicates the number of detents the mouse wheel rotated

41
SDJ International College, Palsana

X It indicates the x-coordinate of mouse click


Y It indicates the y-coordinate of mouse click

SDI and MDI Form


In VB.NET, you can design applications with two main windowing interfaces.
1. SDI (Single Document Interface) Forms
2. MDI (Multiple Document Interface) Forms

SDI (Single Document Interface) Forms:


 In an SDI application, each form represents a single document or view.
 SDI applications typically have multiple forms, but each form is independent
and displays a single document or view at a time.
 Examples of SDI applications include simple text editors or image viewers
where each file is opened in its own window.

MDI (Multiple Document Interface) Forms:


 In an MDI application, there is a parent form that acts as a container for
multiple child forms.
 Each child form in an MDI application represents a document or view, and
these forms are displayed within the parent form.
 MDI applications are useful when you want to have a single main window
with multiple child windows, such as in a word processor where each
document is opened in a separate child window.

How to create Create an MDI form?


 Create a new VB.Net project, and then you will get a default form
Form1 then open the Properties window, set the following properties
IsMdiContainer= true.
Name=frmMDI
Text=MDI form Text(for example Employee Management System)
WindowState=Maximized
 Then add two more forms in the project (Form2 , Form 3)
 Create a Menu on your form (Form1) and call these two forms on menu click
event.
 Then write down the following code on menu click event
Dim frm2 As New
frm2.MdiParent = Me
frm2.Show ()
 Then run your MDI form.

42

You might also like