Unit_2
Unit_2
basic .Net
2.1 IDE
2.2 Variables and Data Types
2.2.1. Boxing and Unboxing
2.2.2. Enumerations
2.2.3. Data Type Conversion Functions
2.2.4. Statements
2.3. String & Date Functions and Methods
2.4. Modules, Procedures and Functions
2.4.1. Passing variable number of arguments
2.4.2. Optional arguments
2.5. Using Arrays and Collections
2.6. Control Flow Statements
2.6.1. Conditional Statements
2.6.2. Loop Statements
2.6.3. MsgBox and InputBox
Examine this screen capture for a few moments. We are not yet in the Visual Basic
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:
Unit 2: Programming in Visual
basic .Net
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 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:
Unit 2: Programming in Visual
basic .Net
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.
Syntax:
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.
Object Object size based on the It can store any type of data defined in a variable of
platform such as 4 bytes in type Object
32-bit and 8 bytes in 64-bit
platform
User-Defined A user-defined data type Each member of the structure has its own data type
(structure) depends on the and limits independent of the other members' ranges.
implementing platform
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
2.2.1. 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:
<access modifier> Enum
enumerationname [ As datatype ]
memberlist
End Enum
Unit 2: Programming in Visual
basic .Net
Example:
Public Class Frmenum
Enum
Temperature
Low
Mediu
m
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
OR
End Sub
dt1 =
Now.ToShortDateString
bolans = IsDate(dt1)
MsgBox(bolans) 'True
strtmep = "testing"
bolans =
IsDate(strtmep)
MsgBox(bolans) 'false
(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) Handlesbtnisnothing.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 =
Unit 2: Programming in Visual
basic .Net
objtemp = "testing"
objans =
IsNothing(objtemp)
MsgBox(objans) 'False
EndSub
(3) IsNumeric: Returns True of the value is numeric, otherwise it returns False
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
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)
(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
Unit 2: Programming in Visual
basic .Net
EndSub
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 comparision.
(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).
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.
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
Unit 2: Programming in Visual
basic .Net
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:
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.
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)
Unit 2: Programming in Visual
basic .Net
Example:
Private Sub btnmath_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnmath.Click
---Remaining
End Sub
Unit 2: Programming in Visual
basic .Net
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 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 Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
Unit 2: Programming in Visual
basic .Net
7) FormatDateTime
Display a date in different formats:
Syntax:
FormatDateTime(date,format)
A value that specifies the date/time format to use. YouCan 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. 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.
OR
<Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>
Statements to Execute
Return return val
End Function
Unit 2: Programming in Visual
basic .Net
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
Procedures:
Procedures are made up of series of Visual Basic statements that, when called, are executed.
After the call is finished, control returns to the statement that called the procedure.
Syntax:
<Access Specifier> Sub Method_Name(<Parameters>)
Statements to Execute
End Sub
Example:
'procedue without argumet
Public Sub
clearcontrol()
txtname.Text =
"" txtadd.Text
= ""
txtage.Text =
""
End Sub
'procedue with argumet
Public Sub hi(ByVal str As String)
MessageBox.Show("hello how r u" &
str)
End Sub
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.
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
swapbyref(txtno2.Text,
txtno3.Text) MsgBox("after
swap")
MessageBox.Show(txtno2.Text)
MessageBox.Show(txtno3.Text)
End Sub
Unit 2: Programming in Visual
basic .Net
Functions:
The Function statement is used to declare the name, parameter and the body of a function.
The syntax for the Function statement is
Syntax:
<Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>
Statements to Execute
Return return val
End Function
Example:
Public Function add(ByVal a As Integer, ByVal b As Integer) As
Integer Return a + b
End Function
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}
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))
Nex
t 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.
Unit 2: Programming in Visual
basic .Net
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.Lengt
h) '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.Lengt
h)
For i = 0 To 10
lstarr.Items.Add(i & vbTab &
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.
Unit 2: Programming in Visual
basic .Net
Example of Array properties
Private Sub btnproperty_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnproperty.Click
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim arrymethod As
Integer 'Property of
Array arrymethod =
list.Length
MessageBox.Show("Lenght of the Array." &
arrymethod) arrymethod = list.GetLength(0)
MessageBox.Show("Lenght of the specified dimension of Array." &
arrymethod) arrymethod = list.GetUpperBound(0)
MessageBox.Show("Returns the highest subscript(index)value." &
arrymethod) arrymethod = list.GetLowerBound(0)
MessageBox.Show("Returns the lowest subscript(index)value." &
arrymethod) arrymethod = list.Rank
MessageBox.Show("gets the rank (number of dimensions) of the
Array." & arrymethod) '1
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.
Unit 2: Programming in Visual
basic .Net
Array List
It represents ordered collection of an object that can be indexed individually.
Example:
Private Sub btnarraylist_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncollection.Click
Dim i As Integer
Dim ItemList As New
ArrayList() ItemList.Add(1)
ItemList.Add("Dhyan")
ItemList.Add("7 years")
ItemList.Add("Boy")
ItemList.Add("Surat")
For i = 0 To ItemList.Count - 1
ListBox1.Items.Add(ItemList.Item(i))
Nex
t End
Sub
Methods of Array List
Private Sub btnarrylistmethod_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncollection.Click
Dim i As Integer
Dim ItemList As New
ArrayList() ItemList.Add(1)
ItemList.Add("Dhyan")
ItemList.Add("7 years")
ItemList.Add("Boy")
ItemList.Add("Surat")
For i = 0 To ItemList.Count - 1
ListBox4.Items.Add(ItemList.Item(i))
Next
' ''Method
Add,insert,remove,RemoveAt,sort
'ItemList.Remove(1)
ItemList.Remove("7 years")
For i = 0 To ItemList.Count - 1
lstremove.Items.Add(ItemList.Item(i))
'MsgBox(ItemList.Item(i))
Next
For i = 0 To ItemList.Count - 1
lstinsert.Items.Add(ItemList.Item(i))
'MsgBox(ItemList.Item(i))
Next
''sort itemms in an
arraylist 'ItemList.Sort()
Example:
Private Sub ifthenelseif_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ifthenelseif.Click
If txtname.Text = "" Then
MsgBox("Enter your
Name") txtname.Focus()
ElseIf txtadd.Text = "" Then
MsgBox("Enter your
Address") txtadd.Focus()
ElseIf txtage.Text = ""
Then MsgBox("Enter
your Age")
txtage.Focus()
Else
MsgBox(txtname.Text & txtadd.Text &
txtage.Text) End If
End Sub
Unit 2: Programming in Visual
basic .Net
(2) You can also specify multiple values with the Case as shown below:
Select Case Grade
Case 10, 9
MsgBox("Excellent
") Case 8, 7
MsgBox("Very
Good") Case 6, 5
MsgBox("Good"
) Case Else
MsgBox("Poor"
) End Select
(3) Do loop
Repeats a block of statements while a Boolean condition is true or false.
Syntax:
Pretest
Do {While/until} condition
Logic
Loop
OR
PostTest
Do
Logic
Loop {While/until} condition
p End
Sub
Do while
Private Sub btndoloop_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btndoloop.Click
Dim num1 As Integer =
1 Do While num1 < 5 '1
to 4
MessageBox.Show("The value of num1 is:" &
num1) num1 = num1 + 1
Loo
p End
Sub
For each…Next
The for each … next loop is similar to the for…next loop but it executes the statements
block for each element in a collection or array Repeats a group of statements for each
element in collection
Syntax
For each element in group
Logic
Next
Example
Print array data for each loop
Private Sub btnforeachnext_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnforeachnext.Click
Dim arr(2), temp As
Integer arr(0) = 10
arr(1) = 20
arr(2) = 30
For Each temp In
arr
MsgBox(temp)
Nex
t End
Sub
Unit 2: Programming in Visual
basic .Net
With…End with
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
.BackColor =
Color.Black End With
End Sub
Messagebox
• Displays a dialog box that can contain text, buttons, and symbols to inform the user.
• It is an advance version of Msgbox function.
• Messagebox is the class and show is the method of it.
Syntax