Unit 2 4
Unit 2 4
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:
3
SDJ International College, Palsana
4. Properties - this window is where property values are set for a given control.
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
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)
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.
5
SDJ International College, Palsana
6
SDJ International College, Palsana
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:
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
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
Exmaple:
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
Example:
12
SDJ International College, Palsana
Example:
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
13
SDJ International College, Palsana
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.
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).
15
SDJ International College, Palsana
16
SDJ International College, Palsana
17
SDJ International College, Palsana
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
18
SDJ International College, Palsana
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
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
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
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
22
SDJ International College, Palsana
Example:
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
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:
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
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.
28
SDJ International College, Palsana
Syntax:
If condition | Then
[statement(s)]
[Elself condition2 Then
[statement(s)]
.
.
[Else
[statement(s)]]
End If
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
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
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
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
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
38
SDJ International College, Palsana
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
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
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.
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
42