0% found this document useful (0 votes)
50 views

Unit-2 .Net Final

The document discusses data types in programming. It describes numeric, character, miscellaneous, and user-defined data types. For numeric types, it provides details on short, integer, long, single, double, and decimal types. For character types, it discusses char and string. For miscellaneous types, it covers boolean, byte, date, and object. It also discusses boxing/unboxing, enumeration, and data type conversion functions.

Uploaded by

devanshi88888888
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)
50 views

Unit-2 .Net Final

The document discusses data types in programming. It describes numeric, character, miscellaneous, and user-defined data types. For numeric types, it provides details on short, integer, long, single, double, and decimal types. For character types, it discusses char and string. For miscellaneous types, it covers boolean, byte, date, and object. It also discusses boxing/unboxing, enumeration, and data type conversion functions.

Uploaded by

devanshi88888888
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/ 52

Created By: Aelisha Joshina Page 1

Created By: Aelisha Joshina Page 2


Created By: Aelisha Joshina Page 3
2.2 Data Type
 The data type of a programming element refers to what kind of data it can
hold and how that data is stored.
 There are mainly four categories of it.
 Numeric Data Types (Short, Integer, Long, Single, Double, Decimal)
 Character Data Types (Char, String)
 Miscellaneous Data Types (Boolean, Byte, Date, Object)
 User-Defined Data Types (structure,array,Enum)

Numeric Data Types


 Short
 It occupies 2 bytes.
 The range of it -32,768 to 32,767.
 Prefix we can use 'sht’ and store only whole number.
 Example: Dim shtRollNo As Short
 shtRollNo = 5

 Integer
 It occupies 4 bytes
 The range of it -2,147,483,648 to 2,147,483,647.
 Prefix we can use ‘int’ and store only whole number
 Example: Dim int RollNo As Short
 intRollno=5

 Long
 It occupies 8 bytes.
 The range of it -9,223,372,036,854,775,808 to 9, 223, 372, 036, 854, 775,807.
 Prefix we can use 'Ing' and store only whole number.
 Example: Dim IngBankIncome As Long
 IngBankIncome = 50000000

 Single
 It occupies 4 bytes.
 The range of it -3.4028235E+38 to -1.401298E-45 for negative value-
1.401298E-45 to 3.4028235E+38 for positive values.
 Prefix we can use 'int' and store whole
 Example: Dim sngSal As Single
 sngSal 5000.5555

 Double
 It occupies 8 bytes.
 The range of it -1.79769313486231570E+308 to -4.94065645841246544E-
324 for negative values; 4.94065645841246544E-324 to
1.79769313486231570E+308 for positive values.

Created By: Aelisha Joshina Page 4


 Prefix we can use 'dbl' and store whole
 Example: Dim dblSatyamFraud As Double
dblSatyamFraud = 2222222222222.5557
 Decimal
 It occuples 16 bytes.
 The range of it 0 to +/-79,228,162,514,264,337,593,543,950,335 with no
decimal point; 0 to +/-7.9228162514264337593543950335 with 28 places
to the right of the decimal; smallest nonzero number is +/-
0.0000000000000000000000000001 (+/-1E-28).
 Prefix we can use 'dec' and store whole
 Example: Dim decIncome As Decimal
 decIncome 1.2321334433243232E+19

 Character Data Types


 It occuples 2 bytes.
 The range of it 0 to 65535.
 Prefix we can use 'ch' and we need to write (" ").
 Example: Dim chGen As Char
 chGen = "M"

 Miscellaneous Data Types


 Boolean
 It occupies 2 bytes.
 It can store either "True" or "False"
 Prefix we can use 'bln'

Example: Dim blnGen As BooleanblnGen True


 Byte
 It occupies 1 byte:
 The range of it 0 to 255.
 Prefix we can use 'byt'
 Usually Byte data type is used to access binary files, image and sound
files etc.
 Example: Dim bytNo As Byte
 bytNo = 223

 Date
 It occupies 8 bytes.
 Minimum value is 0:00:00 on January 1, 0001 and Maximum value.
 11:59:59 PM on December 31, 9999.
 Prefix we can use 'dt' and we need to write (# #)
 The format of Date variable is #mm/dd/yyyy#
 Example: Dim dtDob As Date
 dtDob= #12/21/1982#
 Object
 It occupies 4 bytes.
 It can store any type of data. Prefix we can use ' obj'.

Created By: Aelisha Joshina Page 5


Example:
Dim objTemp As Object
objTemp = 5
objTemp = " Ram"
objTemp = # 10/ 17/ 2008 #
 The Object data type is slower than using explicit data types.
 Object data type is slower than other data type .It takes more time to
fetch and store the data, because it first has to point other memory block
and then perform operation.
 It always uses four bytes in computer memory, but this does not include the storage
for the data representing the value of the variable.
 The Object data type requires more memory than other data types.

2.2.1 Boxing and Unboxing


 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
 The conversion of a value type instance to an object,
 Unboxing
 The conversion of an object instance to a value type.
 Example
Dim no As Integer=10
Dim obj As Object =no' boxing
Dim ans As Integer = CInt(obj)' unboxing

stack heap
num1=10
Address=1002 obj1=10
Address=2004
obj1(ref)
Address=2004

num2=10
figure of Unboxing

stack heap
num1=10
obj1=10

obj1(ref)
figure of Boxing

Created By: Aelisha Joshina Page 6


figure of Boxing and Unboxing

2.2.2 Enumeration
It is used to declare set of constants. You can declare an Enumeration and defines the values
of its member.
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
[<Attribute List>][access modifier]
Enum enumeration_name [As Data Type]
Member1 [=initial expression]
……
MemberN [=initial expression]
End Enum
 Here Access modifier is optional. It specifies that which section can access this
enumeration.
 It can be Public or Private or Protected or Friend. You can specify Protected Friend to
allow access from code within the enumeration's class, a derived class or the same
assembly.
 If you do not use initial expression then member gets initial value 0, member 2 gets
initial value 1 and so on. Even you can also partially assign the initial value to the
members of enumeration.

Created By: Aelisha Joshina Page 7


 The enumeration name is a valid identifier name, and the data type can be mentioned if
necessary, the enumeration data_list or Enum member list represents the set of the
related constant member of the Enumeration.
Example 1: Write a program to understand the uses of enumeration data in VB.NET.
Form1.vb
PublicClassForm1
PublicEnumcource
BCA
MCA
BCOM
BBA
EndEnum

PrivateSub btnenum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnenum.Click
TextBox1.Text = cource.BBA
EndSub
EndClass

4. Data Type Conversion Function


Type conversion is used for convert one data type to another.
 There are two type of conversion:1. Implicit
2. Explicit
 An implicit conversion does not require any special syntax in the source code.
 An explicit conversion requires function.
 In the following example, VB.NET converts the value of A to B.
 Dim A As Integer
 Dim B As Double
 A = 4499
 B=A
As above, The VB.NET will convert smaller data type to larger (Integer Double)
automatically is also called as Narrowing to Widening conversion.explicit conversion.
The following table shows the available conversion functions used for
Function name
CBool Boolean
CByte Byte
CChar Char
CDate Date
CDbl or Val Double
CInt Integer
Created By: Aelisha Joshina Page 8
CDec Decimal
CLng Long
CObj Object
CShort Short
CSng Single
CStr String
Syntax: Function Name (argument)
Example:
Dim str As String Dim str As String
Dim no As Integer Dim dt As Date

str = "5" str = "12/21/1982"


no = CInt(str) dt = CDate(str)

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

Syntax:Ctype (expression, Type name)

Example:
Dim no1 As Integer
Dim no2 As Double
no2 = 66.77
no1 = CType (no2, Integer)
MsgBox (nol)
 Execution is faster because there is no call to a procedure to accomplish the
conversion.
Example:2
PublicClassForm1

PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button2.Click
Dim value1, value2, answer AsInteger
value1 = TextBox1.Text
value2 = TextBox2.Text
answer = value1 - value2
TextBox3.Text = answer
EndSub

PrivateSub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button3.Click
Dim value1, value2, answer AsInteger
value1 = TextBox1.Text
value2 = TextBox2.Text
answer = value1 / value2
TextBox3.Text = answer
EndSub

PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
Dim value1, value2, answer AsInteger

value1 = TextBox1.Text
value2 = TextBox2.Text

Created By: Aelisha Joshina Page 9


answer = value1 + value2
TextBox3.Text = answer
EndSub

PrivateSub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button4.Click
Dim value1, value2, answer AsInteger
value1 = TextBox1.Text
value2 = TextBox2.Text
answer = value1 * value2
TextBox3.Text = answer
EndSub

PrivateSub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button5.Click
Dim dbl AsDouble
Dim iint AsInteger
dbl = TextBox4.Text
iint = dbl
TextBox5.Text = iint

'Integer to double
'iint = TextBox4.Text
'dbl = iint
'TextBox5.Text = dbl

EndSub
EndClass
Output:

Date Convertion
PrivateSub btnisdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnisdate.Click
Dim dt As Date
Dim strtemp As String
Dim boole AsBoolean

dt = Now.ToShortDateString
boole = IsDate(dt)
MsgBox(boole) 'true

strtemp = " testing"


boole = IsDate(strtemp)
MsgBox(boole) 'false
EndSub
EndClass

2.2.4 Option Statements


There are four Option Statements available in VB.NET:
(1) Option Explicit

Created By: Aelisha Joshina Page 10


(2) Option Strict
(3) Option Compare
(4) Option Infer

1. Option Explicit:
It ensures that variables are declared before referring in code. In other words
Explicit forces to declare variable before it is used in the program. The general syntax of
option explicit statement is as follow:
Syntax:
Option Explicit (On / Off}

There are two modes of Option Explicit: On and Off mode. If Option Explicit is
on, variable must be declared before used in the program. Otherwise, it will issue a
compile-time error. By default the Option Explicit is On.

Example:
Option Explicit Off
PublicClassForm1
PrivateSub btnExplicit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnExplicit.Click
'Dim ans As Integer
ans = 10
EndSub
EndClass

Option Explicit On
PublicClassForm1
PrivateSub btnExplicit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnExplicit.Click
'Dim ans As Integer
ans = 10//give an error
EndSub
EndClass

(ii)Option Strict
It ensures that conversion errors are avoided in the code. Option Strict On allows
widening.conversion statements, but a compiler error occurs if a narrowing conversion is
attempt that will cause data loss. The general syntax of option strict statement is as follow:
Syntax:
Option Strict (On / Off" }
It can be set at the top line of code of class files, or on a project level by modifying the
project's properties. By default Option Strict is off.
Example:
Option Strict On
PublicClassForm1
PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
Dim n1 AsInteger
Dim n2 AsDouble
n2 = 9992.36
n1 = n2
MsgBox(n1)
EndSub
EndClass

Created By: Aelisha Joshina Page 11


(iii)Option Compare
It is use to specify whether the conversion string comparison is in binary or text. Its value
can be Binary or Text. By default, it is Text.
The general syntax of option compare statement is as follow:

Syntax
Option Compare (Binary | Text }
Example:
Option Compare Text
PublicClassForm1
PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
Dim a As String = "Hi"
Dim b As String = "good"
‘Dim b As String = "Hi"

If a = b Then
MsgBox(True)
Else
MsgBox(False)
EndIf
EndSub
EndClass

(iv) Option Infer:


 It enables local type inference in declaring variables. When you set On, you can
declare variables without explicitly stating a data type. The compiler infers the data
type of a variable from the type of its initialization expression. When you set Off, and
you do not
specify any data type then it is taken as Object type. The general syntax of option infer
statement is as follow:
Syntax
Option Infer {On | Off}
Example

Created By: Aelisha Joshina Page 12


String & Date functions and methods
String Functions

 Compare
 It's use for comparing 2 strings.
Example:
Int Compare = str. Compare("abc", "ABC", True)
MsgBox(Int Compare, MsgBoxStyle. Information, "Comparison")
Int Compare = str. Compare("ABC", "abc")
MsgBox(Int Compare, MsgBoxStyle. Information, "Comparison")
Int Compare = str.Compare("ABC", "ABC")
MsgBox(Int Compare, MsgBoxStyle. Information, "Comparison")
Output of 1st is 0,2nd -1,3rd is 0.

 Concat:
 Combined 2 strings. Places them one after the other and forms a new string.
 We can use &,+ operators also instead of this.

 Copy:
 Copy string, From source to destination.
 Instead of this we can use directly operator like a=b means copy from b to a
also.

 Equals
 Determines whether two String objects have the same value.

 Trim:
 Removes starting and ending spaces from the string and ending of the string default.
 We can also pass parameter and remove particular character from starting and ending
of the string.
Example:
str = "### Ajit is good boy. ####"
MsgBox(str.Length)

Created By: Aelisha Joshina Page 13


str4 = str.Trim("#")
MsgBox(str4)
MsgBox(str4.Length)

Example:2
PublicClassForm1

PrivateSub btncompar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btncompar.Click
Dim str1 AsString
Dim str2 AsString
str1 = "vb.net"
str2 = "NET"
IfString.Compare(str1, str2) = 0 Then
MsgBox("both are equal")
Else
MsgBox("not equal")
EndIf
EndSub

PrivateSub btnconcat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnconcat.Click
Dim str3, str4 AsString
str3 = "My name is Shyam N. Chawda."
str4 = "My contact no is 9374928879"
str3 = String.Concat(str3, str4)
MsgBox(str3)

EndSub

PrivateSub btncopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btncopy.Click
Dim str5, str6 AsString
str5 = "My name is Shyam N. Chawda."
str6 = String.Copy(str5)
MsgBox(str6)

EndSub

PrivateSub btnequal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnequal.Click
MsgBox(String.Equals("ABC", "xyz"))

'MsgBox(String.Equals("ABC", "ABC"))
EndSub

PrivateSub btntrim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btntrim.Click

Dim str AsString


str = " Hello"
Str = Str.Trim(Str)
MsgBox(str.Length)

EndSub
EndClass

Output:

Created By: Aelisha Joshina Page 14


Dim testString AsString = " <-Trim-> "
Dim trimString AsString
' Returns "<-Trim-> ".
trimString = LTrim(testString)
' Returns " <-Trim->".
trimString = RTrim(testString)
' Returns "<-Trim->".
trimString = LTrim(RTrim(testString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
trimString = Trim(testString)

Self study TrimStart, TrimEnd,Ltrim,RTrim


Ends With
 Checks whether the end of this instance matches the specified String.
 The return type is Boolean.
 It is overload function. We can pass second parameter as case sensitive.

Example:

Public Class Form1

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


System.EventArgs) Handles Button1.Click

Dim test As String = "abcd"


Dim result As Boolean

result = test.EndsWith("e")
TextBox1.Text = (CStr(result))

End Sub
End Class

output:

Created By: Aelisha Joshina Page 15


 Starts With
Exactly opposite of EndsWith. It checks character of starting

Example:

Public Class Form1

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


System.EventArgs) Handles Button1.Click

Dim test As String = "abcd"


Dim result As Boolean

result = test.StartWith("a")
MessageBox.Show = (CStr(result))

End Sub
End Class

output:
 Indexof
 Reports the index of the first occurrence of a String.roda.
Example:

Public Class Form1

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


System.EventArgs) Handles Button1.Click

Dim staff As String = "baseball"


Dim result As String

result = CStr(staff.IndexOf("s"))
TextBox1.Text = result

End Sub
End Class

output

 Ucase, Lcase, ToUpper, ToLower


Example:
Str = "I AM FROM GONDAL SITUATED IN SAURASHTRA"
Str = str.ToLower()
MsgBox(str, MsgBoxStyle.Information, "To Lower")

str = str. ToUpper()


MsgBox(str,
x(str, MsgBoxStyle. Information, "To Upper")

str=LCase(str) ‘It is not part of String class’


MsgBox(str, MsgBoxStyle.Information, "To Lower")

str = UCase(str)
MsgBox(str, MsgBoxStyle.Information, "To Lower")
Insert
 Inserts a specified instance of String at a specified index position in this instance.
 Two arguments it (Start Index, Value). The startIndex means the index position of
the insertion and the Value means The String to insert.
Example:
str = "KABHI ALVIDAA NA KEHNA"
str = str.Insert(5, "abc")
MsgBox(str)
Output: KABHIabc ALVIDAA NA KEHNA

PadLeft, PadRight
Both are used for alignment purpose see the below example.

Example:
str = "I have $ 5000"
str = str.PadLeft(25, "0")
MsgBox(str)
Output: 000000000000I have $ 5000

Example:
str = "I have $ 5000"
str = str.PadRight(25, "0")
MsgBox(str)

Output: I have $ 5000000000000000

 Remove
 Deletes a specified number of characters from this instance beginning at
specified position.
 Two arguments of it (StartIndex,Count).
 StartIndex means the position in this instance to begin deleting characters and count
means the number of characters to delete.

Example:
Public Class Form1

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


System.EventArgs) Handles Button1.Click
Dim str As String = "I have $ 5000"
str = str.Remove(2, 5)
MsgBox(str)
End Sub
End Class

 Replace
 Replaces all occurrences of a specified character or String.
 There are 2 types of arguments of it (Char, Char) and (String,String). It means
overloaded function

Created By: Aelisha Joshina Page 18


Example:
str = "KABHI ALVIDAA NA KEHNA"
TextBox1.Text = str.Replace("A", "B")
Output:KBBHI
KBBHI BLVIDBB NB KEHNB

Example:
str="KABHI ALVIDAA NA KEHNA"
TextBox1.Text = str.Replace("KABHI", "BHABHI")
Output: BHABHI ALVIDAA NA KEHNA
 Substring(IMP)
 Retrieves a substring from this instance.
 There are 2 types of arguments it. (Start Index) and (Start Index,Count).
 StartIndex means from where to start and Count means up to how many
character.
Example:
Public Class substring
Private Sub btnresult_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles result.Click
Dim str As String
str = "hello good
ood morning every one"
str = str.Substring(7)
MsgBox(str)
Output:

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim str As String
str = "hello good morning every one"
str = str.Substring(7, 13)
MsgBox(str)
End Sub
End Class
Output:

 Str.substring(1,1) will give us single digit every time from starting to ending of the
string.

Date-Time Functions
Dim dt As Date
REM: Simple store date
dt = #12/21/1982# 'MM/DD/YYYY'
Get the current date or time

txtDate.Text = Today 'Stores 8/15/2009


txtDate.Text = Now 'Stores 8/15/2009 9:34:07 PM
txtDate.Text = TimeOf Day 'Stores 9:35:15 PM
txtDate.Text = Date String '08-15-2009
txtDate.Text = TimeString 'Stores 21:36:17

Return a date
txtDate.Text = DateSerial(2009, 2, 1) 'Returns 2/1/2009
txtDate.Text = DateValue("10/26/1995") 'Returns 10/26/1995

Return Time
txtDate.Text = TimeSerial(10, 5, 45) 'Returns 10/26/1995
txtDate.Text = TimeValue("4:35:17 PM") ‘Returns 10/26/199
txtDate.Text = TimeValue(#4:35:17 PM#) 'Returns 4:35:17 PM

Format Function

 Returns a string formatted according to instructions contained in a form


String expression.
 There are 2 arguments of it an expression and style.
txtDate.Text = Format(Now, "M-d-yy")
"M 'Stores 5-5--08
txtDate.Text = Format(Now, "MM-dd-yyyy")
"MM 'Stores 05-05
05-2008
txtDate.Text = Format(Now,
(Now, "MMMM-d-yyy
"MMMM dddd") 'Stores May-05-
May 2008
Tuesday
txtDate.Text = Format(Now, "hh:mm:ss tt") 'Stores 09:58:51 PM
 String Methods
As given below are the some of char class's methods:

Name Description of methods


IsDigit Checks a character is decimal digit or not
IsLetter Checks a character is an alphabetic letter or not
IsLetterOrDigit Checks a character is an alphabetic letter or a decimal digit
IsLowerIsLower
Checks a character is lowercase letter or not.
IsNumber Checks a character is number or not.
I IsPunctuation Checks a character is punctuation mark or not.

IsIsSeparator Checks a character is separator character or not

I IsSymbol Checks a character is symbol character or not.

Checks a character is an uppercase letter or not.


IsUpper
Checks a character is white space or not
IsWhitespace
T ToLower Converts the value of a character to its lowercase.

ToUpper Converts the value of a character to its uppercase

Example:
Imports System.Char
PublicClassForm1

PrivateSub btnstring_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnstring.Click
'IsDigit
MsgBox(IsDigit("8"))
MsgBox(IsDigit("Sample string", 7))
EndSub

PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button2.Click
'IsLetter
MsgBox(IsLetter("8"))
MsgBox(IsLetter("Sample string", 7))
EndSub

Created By: Aelisha Joshina Page 21


PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
'IsLower
MsgBox(IsLower("8"))
MsgBox(IsLower("Sample string", 7))
EndSub

PrivateSub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button3.Click
'IsNumber
MsgBox(IsNumber("8"))
MsgBox(IsNumber("Sample string", 7))
EndSub

PrivateSub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button4.Click
'IsPunctuation
MsgBox(Char.IsPunctuation("8"))
MsgBox(IsPunctuation("Sample string", 7))
EndSub

PrivateSub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button5.Click
'IsSeparator
MsgBox(IsSeparator("8"))
MsgBox(IsSeparator("Sample string", 7))
EndSub

PrivateSub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button6.Click
'IsSymbol
MsgBox(IsSymbol("8"))
MsgBox(IsSymbol("Sample string", 7))
EndSub

PrivateSub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button7.Click
'IsUpper
MsgBox(IsUpper("8"))
MsgBox(IsUpper("Sample string", 7))
EndSub

PrivateSub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button8.Click
'IsWhiteSpace
MsgBox(IsWhiteSpace("A"))
MsgBox(IsWhiteSpace("Sample string", 7))
EndSub

PrivateSub Button9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button9.Click
'ToLower

MsgBox(ToLower("D"))

EndSub

PrivateSub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button10.Click
'ToUpper
MsgBox(ToUpper("d"))
EndSub
EndClass

Created By: Aelisha Joshina Page 22


output:

2.4 Modules, Procedures and Function

Module
It is a file to store group of functions in a single unit. User can write several procedures in the module and
that can be used on different forms and classes in the application.

 Adding module in the project


a) In solution explorer, Right click on project
b) Select Add from popup menu
c) Select Module
d) Give Proper name
e) Click on Add button

 Another way to add Module in the project it as follow:


a) In solution Explorer, Right Click on project
b) Select Add from popup menu
c) Select New Items
d) From Template select Module
e) Give Proper Name
f) Click on Add button
PROCEDURE:
 A procedure is a set of one or more program or call by referring to the procedure name.
 We can divide the big program into small procedures.
 Due to Procedure the application is easier to debug and easier to find error.
 Reusability of procedure is the one of the great advantage of it.
 A Procedure have 2 categories In-built or User-defined procedures.

There are four types of Procedures in VB.Net

Sub procedures does not return value.

Event-handling procedures are Sub procedures that execute in response to an event triggered by user
action. Like button1_Click

Function procedures return a value.

Property procedures used in object oriented concept.

Modular Coding

There are 2 approaches for doing modular coding in VB.net

1. Sub Routines or Sub Procedure


2. Function Procedure

 The main concept is breaking large application into smaller.


 If your procedure does not return any value then it should be implemented as a sub procedure
else function.
 The approach of modular coding is dividing conquer approach.
Module Module1

Sub SubDivide(ByVal num1 As Integer, ByVal num2 As Integer)

Dim res As Integer

If (num2 <> 0) Then


res = num1 / num2
Console.WriteLine("Divide by Zero is possible")
Else
Console.WriteLine("Divide by Zero is undefined")
End If
End Sub
Sub Main()
Dim a As Integer
Dim b As Integer
Dim res As Integer
Console.Write("Enter Number 1")
a = Console.ReadLine()
Console.Write("Enter Number 2")
b = Console.ReadLine()
SubDivide(a, b)

Console.WriteLine(res)
Console.ReadLine()
End Sub

End Module

Created By: Aelisha Joshina Page 25


Sub Procedures
 A sub procedure is nothing more than a small block of program in itself.
 It is also known as Sub Routine.

There are 2 parts of it declaring and calling.

 We should give proper name to it through which we can remember it easily.


 Sub procedure may or may not have arguments. Arguments are not compulsory.
 Sub procedure does not return the value.
 By Val is by default argument type. So do not worry to type it. It will automatically appear if we set
parameter in the Sub procedure.

Syntax:

[Accessibility] Sub subname (argument list)

Logic...

End Sub

 The accessibility can be Public, Protected, Friend, Protected Friend Private.


 By default accessibility is Public.

Example:Create Sub Procedure when user click on button call it

PublicClassprocedure
'procedure without arguments
Sub hii()
MsgBox("goood morning")
End Sub

PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
'call procedure without arguments
Call hii()
End Sub
EndClass

 We can call sub procedure using Call keyword or without Call keyword.
 When we declare procedure it will automatically appear in the context menu as given below.

Change our sub procedure and write down below coding:

Example:With argument Sub Procedure.


Public Class Form2
'procedue with argumet
Public Sub hi(ByVal str As String)
MessageBox.Show("hello how r u" & str)
End Sub
Private Sub btnans_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnans.Click
'call procedure with arguments

Created By: Aelisha Joshina Page 26


Call hi("Aelisha")

End Sub
End Class

Function :

 A Function procedure is similar to a sub procedure, but it returns a value to the calling program.
 Function procedure may or may not have arguments.
 Here statements enclosed by the Function and End Function.
 By Val is by default argument type.
 As clause is written after the parameter list is set.
 Because function can return the value we can function using:
Somvariable=functioname(arguments)
 Function runs the logical and returns the value in that variable.
 By default functions are public.

Syntax:

[accessibility] Function function[(argument list)] As Returndatatype

Logic…

[Return value]

End Function

With Module Example:


Module Module1

Sub SubDivide(ByVal num1 As Integer, ByVal num2 As Integer)

Dim res As Integer

If (num2 <> 0) Then


res = num1 / num2
Return res
Console.WriteLine("Divide by Zero is possible")
Else
Console.WriteLine("Divide by Zero is undefined")
End If
End Sub
Sub Main()
Dim a As Integer
Dim b As Integer
Dim res As Integer
Console.Write("Enter Number 1")
a = Console.ReadLine()
Console.Write("Enter Number 2")
b = Console.ReadLine()
SubDivide(a, b)

Console.WriteLine(res)
Console.ReadLine()
End Sub

End Module

Created By: Aelisha Joshina Page 27


Function Calling syntax
Private Sub btnAns_Click(ByVal sender As System. object

lblAns.Text=Square(No As Integer)As Integer

End Sub
Return type
Function Name

Argument

With Function Example:


'Addiction function
'Example-2
Public Function add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnfun.Click
Dim ans As Integer = add(txtno1.Text, txtno2.Text)
MsgBox(ans)
End Sub

2.4.2 Optional arguments


 We can specify procedure argument as an optional.
 In C ++ this concept is known as default argument.
 Optional means not to pass argument compulsory when the procedure is called.
 > They are indicated by the Optional keyword in the procedure else if we pass then default value is
overwritten.
 If we do not pass the value of optional argument then it will take its default

 Some rules of the optional argument


 Remember that if we make one argument optional, all the following arguments must be optional.
 We must specify a default value for every optional argument.

Syntax:
Sub subProcName (para1 as< type>, optional para2 as< type> = value)

End Sub

Function funcName (para1 as< type>, optional para2 as< type> = value) as

< type>

End Function

Created By: Aelisha Joshina Page 28


Example: Create Add sub procedure which contains second argument as optional Argument.
Public Class Form1
Sub add(ByVal no1 As Integer, Optional ByVal no2 As Integer = 0)
MsgBox(no1 + no2)

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnans.Click
add(5)
End Sub
End Class

Calling Syntax:

add(5)

Or

Call add(5,2)

2.5 Using Arrays and collection


 Array is a collection of elements of same data type.
 Array elements are accessed using a single name an index number, representing position
of the element within the array.

Syntax:

Dim Array_name (no_of_elements) As Data type

Example:
Private Sub btnArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnArray.Click
lstarr.Items.Clear()
Dim num(4) As Integer
num(0) = 10
num(1) = 20
num(2) = 30
num(3) = 40
For i = 0 To 3
lstarr.Items.Add(num(i))
Next
End Sub
There is another way to create an array. A user can initialize array elements at the time of declaration. The
general syntax to initialize an array at the time of declaration is as follow:

• Multidimensional Array: User can also create multidimensional array. The general syntax
of a multidimensional array declaration is as follow:

Syntax

Dim Array_name ([Lower_Bound, Upper_Bound]) As Integer


Created By: Aelisha Joshina Page 29
 Length: The length of an array is the total number of elements it can contain.

Example

Dim Mat (2, 2) As Integer

Dim Mat () As Integer = New Integer (2, 2) {}

User can initialize 2-Dimensional Array as

• Assigning values to Array elements

After declaring an array, user can assigned a value to an array element. The general for
assigned a value to an array element is as follow:

Syntax

Array_name (index) =value


Example

Dim Num (9) As Integer

Num (0) =5

Dim Mat (2, 2) As Integer

Mat (0,0) =5

 Rank: It returns number of dimensions in the array.


 GetUpperBound: Returns highest subscript(index) value of specified dimension in the
array.
 GetLowerBound: Returns Lowest Index of the specified dimension in the array.

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


btnarraymix.Click
Dim ar(1, 2) As Integer

Dim i, j As Integer
ar(0, 0) = 1
ar(0, 1) = 2
ar(0, 2) = 3

ar(1, 0) = 4
ar(1, 1) = 5
ar(1, 2) = 6

MsgBox(ar.Length)
MsgBox(ar.Rank)

MsgBox(ar.GetLowerBound(0))
MsgBox(ar.GetLowerBound(1))

Created By: Aelisha Joshina Page 30


MsgBox(ar.GetUpperBound(0))
MsgBox(ar.GetUpperBound(1))

For i = 0 To ar.GetUpperBound(0)
For j = 0 To ar.GetUpperBound(1)
txtans.Text &= Space(5) & ar(i, j)
Next
txtans.Text &= vbNewLine
Next
End Sub

 Resizing Array Statement(IMP)


We can increase the size of the array.

You can resize an array using ReDim keyword.


When we ReDim an array, its existing values are normally lost.

Syntax

ReDim [Preserve] array_name(new size of an array)

Example

If you want to resize Num Array to hold 20-elements then

ReDim Num (20)

When you use ReDim Statement, the existing contents are erased. You can use Preserve
keyword to ensure that the existing contents of an array are not lost.

Example

ReDim Preserve Num (20)

If you use Preserve keyword while resizing an array, only the last dimension of the array can
be resized.

Example
Private Sub btndeclare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btndeclare.Click
Dim Rollno(2) As Integer
Rollno(0) = 1
Rollno(1) = 2
Rollno(2) = 3

Dim i As Integer
ReDim Rollno(10)

// ReDim Preserve Rollno(10)


For i = 0 To Rollno.GetUpperBound(0)
lstarr.Items.Add(Rollno(i))
Next
End Sub

Created By: Aelisha Joshina Page 31


 Erase Statement

It is used to release array variables and deallocate the memory used for their elements.

general syntax of Erase element is as follow:

Syntax

Erase Array_namel [, array_name2 [, array_name3 ...]]


Example
Dim Num (9) As Integer

Erase Num

 Traversing can access


A user can access all elements of an array using the following code:

Example
Dim Num (3) As Integer

Num (0) = 1

Num(1) = 2

Num (2) = 3

Num (3) = 4

For I As Integer = 0To 3

MessageBox.Show(Num (I) .ToString)

Next

Output

Created By: Aelisha Joshina Page 32


 Built-In Function
User can perform different operations on an array. Table 1 shows the list of function that are applied on
an array.

Functions Description
GetUpperBound It gets the upper bound of the specified dimension in the Array.
GetLowerBound It gets the lower bound of the specified dimension in the Array.
GetLength It gets the number of elements in the specified dimension of the Array.
GetType It gets the data type of the Array.
First It gets the first element of an Array.
Last It gets the last element of an Array.
Max It gets the maximum element of an Array.
Min It gets the minimum element of an Array.
IndexOf It gets the index of the specified element of Array.

Example:
Dim Num () As Integer = {1, 2, 3}
Dim Res As Integer
Res = Num. Get Upper Bound (0)
Message Box.Show (" GetUpper Bound =" + Res.ToString)

Res= Num. GetLowerBound(0)


Message Box.Show (“GetLower Bound =" + Res.ToString)

Res=Num.GetLength(0)
Message Box.Show (" GetLength = " + Res. ToString)

Message Box.Show ("GetType =" + Num. GetType (). ToString)

Res-Num. First
Message Box.Show(" First Element=" + Res. ToString)

Res-Num. Last
Message Box.Show ("Last Element =" + Res.ToString)

Res-Num. Max
Message Box.Show ("Max-" + Res. ToString)

Res-Num. Min
Message Box.Show ("Min =" + Res.ToString)

Res = Array IndexOf (Num, 2)


Message Box.Show ("Index of =" + Res. ToString)
Created By: Aelisha Joshina Page 33
Output: The following output is displayed in the message box.
GetUpperBound=2
GetLowerBound=0
GetLength= 3
GetType-System.Int32 []
First Element = 1
Last Element=3
Max = 3
Min=1
Index of= 1

• Array of Array
 It is possible to create more complicated structures for storing data, such as array of arrays.
 If an array is declared as Object, it is possible to assign other types to its elements, including arrays.
 Suppose there are two arrays, one with integers and another with strings, then an Object type array
can be declared with two elements and populate it with the two arrays i.e.of integer and string.

Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnarr.Click
Dim sArr(9) As String
Dim iArr(4) As Integer
Dim oArr(1) As Object
Dim i As Integer
For i = 0 To 4
' assign value to iArr array
iArr(i) = i
Next ' assign value to sArr array
For i = 0 To 9
sArr(i) = " Str " & i.ToString(" 0000 ")
Next
oArr(0) = iArr
oArr(1) = sArr
MessageBox.Show(oArr(0)(3))
''fourth element of iArr in oArr
MessageBox.Show(oArr(1)(6))
' seventh element of sArr in oArr

End Sub
Output: The following output is displayed in the message box.

Str 0006

In the above example, oArr was declared as a one-dimensional array, but because each of its elements is an
array, you must use two indices to access it. To access the fourth element of iArr in oArr, the use indices 0
and 3. Likewise, the seventh element of the sArr in oArr is oArr (1) (6).

Created By: Aelisha Joshina Page 34


 Array Methods:
Private Sub btnmethod_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnmethod.Click
'Get Value
Dim nameLen(6) As Integer
Dim name(6) As String

name(0) = "Elisha"
name(1) = "Shivansh"
name(2) = "Devang"
name(3) = "Joshina"
name(4) = "ABC"
name(5) = "XYZ"
name(6) = "PQR"

'set value
'name.SetValue("Aelisha", 0)
'name.SetValue("Shiv", 1)
Dim i As Integer
For i = 0 To name.GetUpperBound(0)
lstarr.Items.Add(name.GetValue(i))
'lstarr .Items .Add (name.SetValue ("a",i)
Next

'sorting
lstarr.Items.AddRange(name)
System.Array.Sort(name)
ListBox1.Items.AddRange(name)
For i = 0 To name.GetUpperBound(0)
nameLen(i) = Len(name(i))
ListBox1.Items.Add(name(i) & "" & Len(name(i)))
Next

'Reverse
lstarr.Items.AddRange(name)
Array.Reverse(name)
ListBox1.Items.AddRange(name)
End Sub
End Class

 Collections
A collection is a one-dimensional storage area which holds value of mixed data types.

Collections are increased in size simply by adding items to it. A collection is declared with a Dim statement
that creates a new Collection object.

Syntax:

Dim Cname As New Collection.

 Adding Item In Collection.---add()

Syntax:

Cname.Add(Value,Key)

Ex: Cname.Add(“Sonam Kapoor”,”Sk”)

Created By: Aelisha Joshina Page 35


 Access Item Of Collection:--item()

Syntax:

Cname.Item(Index) or Cname.Item(Key)

 Items in a collection are indexed beginning with 1.


Ex: Cname.Item(1) or Cname.Item(“Sk”)

The collection is part of the System. collection class.

Below table represents some of the collection.

Class Description
ArrayList Size is dynamically increased as required.
Hashtable Represents a collection of key/value pairs.
SortedList Represents a collection of key/value pairs that are sorted by the keys and are accessible
by key and by index.
A collection is declared with a Dim statement that creates a new Collection object.

The following statement declares a collection of cities.

Dim cities As New collection

 Array List collection


 Array list is a collection of objects.
 It can grow dynamically, we can add elements in it at runtime.
Example:
PublicClassForm1
Dim ar As New ArrayList
Dim str As String
Private Sub btnarraylist_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnarraylist.Click
MsgBox(ar.Count)
ar.Capacity = 25
Call AddArrayRange()
MsgBox(ar.Count)

End Sub
Sub AddArrayRange()
' Dim ar As New ArrayList
Dim str(4) As String
str(0) = "a"
str(1) = "b"
str(2) = "c"
str(3) = "d"
str(4) = "e"
ar.AddRange(str)

End Sub
Private Sub Btnarraylistcount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Btnarraylistcount.Click
Dim ar As New ArrayList
ar.Add("Surat")
ar.Add("Vadodra")

Created By: Aelisha Joshina Page 36


ar.Add("Bharuch")
ar.Add("kim")
MsgBox(ar.Count)

End Sub

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


Handles btnarraylistclear.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("Surat")
ar.Add("Vadodra")
ar.Add("Bharuch")
ar.Add("kim")

For Each str In ar


ListBox1.Items.Add(str)

Next
MsgBox(ar.Count())
ar.Clear()
MsgBox(ar.Count())

End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnadd.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("Surat")
ar.Add("Vadodra")
ar.Add("Bharuch")
ar.Add("kim")
Dim ar2 As New ArrayList
ar2 = ar.GetRange(0, 3)
For Each str In ar
ListBox1.Items.Add(str)
Next
For Each str In ar2
ListBox2.Items.Add(str)
Next

End Sub

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


btninsert.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("A")
ar.Add("B")
ar.Add("e")
ar.Add("D")
ar.Insert(2, "c")
For Each str In ar
ListBox1.Items.Add(str)

Next

End Sub

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


btninsertrange.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("abc")
ar.Add("efg")
ar.Add("ghy")
For Each str In ar
ListBox1.Items.Add(str)
Next

Created By: Aelisha Joshina Page 37


Dim strarr(4) As String

strarr(0) = "a"
strarr(1) = "b"
strarr(2) = "c"
strarr(3) = "d"
strarr(4) = "e"

ar.InsertRange(2, strarr)
For Each str In ar
ListBox2.Items.Add(str)
Next

End Sub

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


btnreverse.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("A")
ar.Add("B")
ar.Add("C")
ar.Add("D")
ar.Insert(4, "E")
For Each str In ar
ListBox1.Items.Add(str)

Next
ar.Reverse()
For Each str In ar
ListBox2.Items.Add(str)
Next

End Sub
Private Sub Btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Btnremove.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("A")
ar.Add("B")
ar.Add("C")
ar.Add("D")

For Each str In ar


ListBox1.Items.Add(str)

Next
ar.Remove("D")

For Each str In ar


ListBox2.Items.Add(str)

Next

End Sub
Private Sub btnsort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnsort.Click
Dim ar As New ArrayList
Dim str As String
ar.Add("Aelisha")
ar.Add("Joshina")
ar.Add("Nency")
ar.Add("pooja")
ar.Add("Komal")
ar.Add("Himani")

Created By: Aelisha Joshina Page 38


For Each str In ar
ListBox1.Items.Add(str)

Next
ar.Sort()

For Each str In ar


ListBox2.Items.Add(str)

Next

End Sub
EndClass

Output:

 HashTable:
 Hashtable is storing data in key-value pair,where key field will remain unique.
 Elements can be searched using key value.
 HashTable allows you to access the items by a key.Each item has a value and a key.

Example:
PublicClasshash_table

PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
Dim h1 AsNewHashtable
h1.Add(1, "abc")
h1.Add(12, "bb")
h1.Add(32, "ccc")
h1.Add(43, "dddd")
h1.Add(55, "eeeee")

Dim key AsObject

ForEach key In h1.Keys


MsgBox(h1(key))
Next
EndSub
EndClass

 Sorted List:

Created By: Aelisha Joshina Page 39


 It’s a combination of the Array and HashTable.
 List can be accessed by either an index or a key.
 A SortedList internally maintains two arrays to store the elements of the list;that is,one array
for the key and another array for the associated value.

Example:
PublicClasssorted_list
'Dim s1 As New sortedlist
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim s1 AsNewSortedList
Dim i AsInteger
s1.Add(1, "ab")
s1.Add(21, "cdd")
s1.Add(12, "nn")
s1.Add(5, "mm")
For i = 0 To s1.Count - 1
ListBox1.Items.Add(s1.GetKey(i))
Next
For i = 0 To s1.Count - 1
ListBox2.Items.Add(s1.GetByIndex(i))

Next
EndSub
EndClass

Output:

Difference between Array and Collection

Sr.
Key Arrays Collection
No.
Arrays are fixed in size i.e once the array
The collection is dynamic in size i.e based
1 Size with the specific size is declared then we
on requirement size could be get altered
can't alter its size afterward. even after its declaration.
Collections, on the other hand, consume
Memory Arrays due to fast execution consumes
2 less memory but also have low
Consumption more memory and has better performance.
performance as compared to Arrays.
Arrays can hold the only the same type of
data i.e only homogeneous (data structures Collection, on the other hand, can hold
3 Data type are those in which data of same type can be both homogeneous and heterogeneous
stored) data types elements are allowed in elements.
case of arrays.
4 Primitives Arrays can hold both object and primitive On the other hand, collection can hold

Created By: Aelisha Joshina Page 40


Sr.
Key Arrays Collection
No.
storage type data. only object types but not the primitive
type of data.
Arrays due to its storage and internal Collection on the other hand low
5 Performance
implementation better in performance. performance compare to array.

2.6 Control Flow Statements


> It is used to decide the flow of program.

> Control statements enable us to execute a certain set of statements based

condition.

> The condition is evaluated runtime and depending on the result of condition

block of code will execute.

> Control Structure also known as Branching statements or Test Structure or Decision Structure.

> Control Structure includes:

1.If…Then..Else

2.Select case

If...Then...Else

There are cases when we would like to execute some logic when a condition TRUE, and some other logic
when the condition is FALSE.

The condition usually results from a comparison of two values.

If the condition is TRUE then the control goes to between IF and Else block, that is the program will execute
the code between IF and ELSE statements.

If the condition is FALSE then the control goes to between ELSE and END IF block, that is the program will
execute the code between ELSE and END IF statements.

We can write only If block. The ElseIf and Else clauses are both optional.

We can have any number of ElseIf statements or none.

We can use If..Then..Else block to evaluate more than one condition.

We can also write nested If..Then..Else block.

Then keyword is used with If.. and Elself.. Statements.

Syntax:

If condition Then

Logic…
Created By: Aelisha Joshina
ElseIf condition-n Then Page 41
Example: Single If block
Private Sub btnAns_Click(ByVal sender As System.

If IsNumeric(txtNo. Text) Then

lbl Ans. Text= "Yes data is numeric"

End If

End Sub

End Class

Example:If…else block

Public class
Private Sub if_else_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
If TextBox1.Text Mod 2 = 0 Then
Label1.Text = "No is even"
Else
Label1.Text = "No is odd"
End If
End Sub
End Class

Example: If..ElseIf..else block

Example:1
Private Sub btnresult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnresult.Click

Created By: Aelisha Joshina Page 42


Dim no1, no2 As Integer
no1 = txtnumber1.Text
no2 = txtnumber2.Text
If no1 > no2 Then
lblans.Text = no1 & " is maximum"
ElseIf no2 > no1 Then
lblans.Text = no2 & "is maximum"
Else
lblans.Text = "both are same"
End If
End Sub

Example:2
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim pct As Double
'CDbl (Function) Converts any expression to a Double.
' This function accepts any expression convertible to a Double, including strings. A runtime error
is generated if expression is Null.

If pct > 90 Then


txtletter.Text = "A"
ElseIf (pct > 80) Then
txtletter.Text = "B"
Else
txtletter.Text = "F"
MsgBox(CDbl(txtgrade.Text))
EndIf
EndSub

PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load

EndSub
EndClass

Output:

Created By: Aelisha Joshina Page 43


We can also use logical operators in If..Then..Else block like below:

Example:
Private Sub btnifthenelseif_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnifthenelseif.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
Select....Case

>When you are comparing the same expression with several different values, we can use the Select...Case
statements as an alternative to the If...Then...Else statements.

>It executes one of several groups of statements depending on the value of an expression.

> If. Then..Else block executes different condition or expression in each statement, the Select statement
evaluates a single expression and compares it for every comparison.

>It's possible in If..Then.. Else block to satisfy multiple If and ElseIf conditions then multiple logic will run,
but If multiple Case statements are True, only the statements belonging to the first true Case statement
are executed.

>If any Case statement is satisfied logic will run that only and then control will come out of Select block.
This one will not happen with If...Then..Else block.

>If..Then..Else block are time consuming then Select case block.

.> We can add any number of Case statements, and we can include or remove a Case Else statement

Created By: Aelisha Joshina Page 44


> If no one Case statement is satisfied then Case Else clause's logic will run.

> Case Else is an optional statement. If used, the Case Else must be the last Case clause. Otherwise it will
execute all the time.

> We can use the To keyword to specify a range of values.

>We can also use Is keyword. The Is keyword is used with any comparison
Syntax:

Select Case testexpression

Case expressionist-n

Logic...

Case Else

Logic….

Example: Enter age and display category


PublicClassForm1

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


Button2.Click
Dim age As Integer = (CInt(txtageselectcase.Text))
Select Case age
Case 2
lblmsgans.Text = "you are infant"
Case 3, 4
lblmsgans.Text = "you are in sr. or gr. kg"
Case 5 To 12
lblmsgans.Text = "you are in primary section"
'TO keyword use for specify a range of values
Case 12 To 15
lblmsgans.Text = "you are in secondary section"
'Is keyword used for any comparison operators.
Case Is < 18
lblmsgans.Text = "you are in Higher Secondary section"
Case Else
lblmsgans.Text = "No idea"
End Select
End Sub
EndClass

Output:
 Loop Statements
 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
1. While...End While
2. Do ....Loop
3. For..Next
4. for-each loops.
 While...... Loop
 While Loop runs set of statements as long as the condition specified with While loop is True.
Syntax:
While condition
[Statements]
End While

Example
Private Sub btnwhileloop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnwhileloop.Click
Dim num1 As Integer = 1
While num1 < 10
MessageBox.Show("The value of num1 is:" & num1)
num1 = num1 + 1
End While

End Sub

 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 and exit-control loop.

Syntax

Do {While/Until} Condition
Logic....
Loop

 We can use either While and Until.


 While: Repeat the loop until condition is False
 Until : Repeat the loop until condition is True

Example 1:

Created By: Aelisha Joshina Page 46


Private Sub btndowhile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btndowhile.Click
Dim num1 As Integer = 1
Do While num1 < 5 '1 to 4
MessageBox.Show("The value of num1 is:" & num1)
num1 = num1 + 1

Loop
'While repeat the loop until condition is false
End Sub

Example 2:
Private Sub btndoloop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btndoloop.Click
Dim num1 As Integer = 1
Do Until num1 = 5
MessageBox.Show("The value of num1 is:" & num1)
num1 = num1 + 1
Loop
'Until:-repeat the loop untill condition is true
End Sub

 For .... Next


 The For loop executes a block of statements a specified number of times.
 It’s most commonly and most popular loop used in any programming language.
 Remember Next keyword should be used in For....Next at the end.
Syntax:
Syntax:
For counter = start To end [Step increment/decrement]
Logic..........
Next

 Here counter variable is initialized when the loop starts and runs up to the end values.
 We can set increment and decrement by step keyword.
 Step keyword is optionally to write.
 By default loop will increment by 1.

Example
Private Sub btnfornext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnfornext.Click
Dim i As Integer
For i = 0 To 10
MessageBox.Show("The value of i is:" & i)
Next
End Sub
For each Loop
We will discuss in topic 2.5 Array and Collection

Created By: Aelisha Joshina Page 47


Example

Private Sub btnforeach_Click(


btnforeach_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnforeach.Click
Dim arr(2), temp As Integer
arr(0) = 10
arr(1) = 20
arr(2) = 30
For Each temp In arr
MsgBox(temp)
Next
End Sub

 MsgBox(),, MessageBox.Show
MessageBox.Show() and InputBox()
 MsgBox()
 Displays a message in a dialog box.
 It interrupts the user that means it immediately blocks further interactions.
 It requires only one function call.
 W specify Button , waits for the user to click a button, and returns an Integer
indicating which button the user clicked.
Syntax
Ans=MsgBox (prompt, [ bbuttons+Icon ] ,[ title])

 Prompt is compulsory argument.


 Buttons and Icon is optional argument.
 By default title is Project Name

Example: 1- MsgBox("MsgBox
"MsgBox Prompt"
Prompt", MsgBoxStyle.YesNo, "MsgBox Title")
Title"
Example: 2-
Private Sub Button1_Click(ByVal
ByVal sender As System.Object, ByVal e As System.EventArgs)
System.
Handles Button1.Click
'MsgBox("Hi Welcome msgbox")
Dim ans As Integer
ans = MsgBox("can
"can you give me answer?"
answer?", MsgBoxStyle.Information
.Information +
MsgBoxStyle.YesNoCancel)
If ans = 6 Then
MsgBox("thanks")
ElseIf ans = 7 Then
MsgBox("why No..?"))
ElseIf ans = 2 Then
MsgBox("why
"why cancel"
cancel")
End If
End Sub

Created By: Aelisha Joshina Page 48


The list of button below and the return value of it.
Value Button
1 vbOK
2 vbCancel
3 vbAbort
4 vbRetry
5 vbIgnore
6 vbYes
7 vbNo

Some of the values of argument style as given below:

Constant Description
OKOnly Display OK button only.
OKCancel Display OK and Cancel buttons.
AbortRetryIgnore Display Abort, Retry, and Ignore buttons.
YesNoCancel Display Yes, No, and Cancel buttons.
YesNo Display Yes and No buttons.
RetryCancel Display Retry and Cancel buttons.
Critical Display Critical Message icon.
Question Display Warning Query icon.
Exclamation Display Warning Message icon.
Information Display Information Message icon.
DefaultButton1 First button is default.
DefaultButton2 Second button is default.
DefaultButton3 Third button is default.
DefaultButton4 Fourth button is default.

 MessageBox.Show
 It's an advance version of MsgBox function.
 MessageBox is the class and Show is the method of it.
 Show method has more arguments then MsgBox function. It contains separate arguments for
icon and button.
 It also provides alignment option, helpbutton and default button options.
Syntax:
MessageBox.Show(Text,caption,button,icon,defaultbutton, options,help)

Created By: Aelisha Joshina Page 49


Example:
Private Sub Button2_Click(ByVal
ByVal sender As System.Object, ByVal e As System.EventArgs)
System.
Handles Button2.Click
MessageBox.Show("welcome"
"welcome", "Demo", MessageBoxButtons.YesNo,
MessageBoxIcon.Error, MessageBoxDefaultButton
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign,
.RightAlign, True)
'MessageBox.Show("welcome", "demo")
End Sub

Output:

 InputBox
 InputBox function is to accept data from th
the user.
 An InputBox function will display a prompt box where the user can enter a value or a
message in the
form of text.
 Instead of taking Textbox on the form we can get the user value using InputBox.
 The Inputbox function with return a va
value.
lue. We need to declare the datatype for values to be
accepted
in the Inputbox
Syntax:
Ans=InputBox(Prompt, Title, default_text, xx-position, y-position)
 The prompt argument will be displayed as message when a question is asked.
aske
 Thetitle argument is the title of the Input Box.
 The default_text argument appearsthe Input field where users can use it as his intended
input or he may change
to the message he wish to key in and xx-position and y-position
position are the position or the
coordinate of the
Inputbox.

Created By: Aelisha Joshina Page 50


Example: 1:Accept the message from InputBox and display name in the messagebox.

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


Dim ans AsString
ans = InputBox("What is your message?", "Message Entry Form", "Enter your message
here")
MsgBox("My Name is:"& ans)
End Sub

OutPut:

Example: 2:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button3.Click
Dim result As String
result = InputBox("Enter name", "Info", "Hrere")
MsgBox(result, , "Result")
End Sub

Created By: Aelisha Joshina Page 51


Created By: Aelisha Joshina Page 52

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy