Advertisements
Advertisements
Advertisements
NetQuickGuide
VB.NetQuickGuide
Advertisements
PreviousPage NextPage
VB.NetOverview
Visual Basic .NET (VB.NET) is an objectoriented computer programming language
implemented on the .NET Framework. Although it is an evolution of classic Visual Basic
language,itisnotbackwardscompatiblewithVB6,andanycodewrittenintheoldversion
doesnotcompileunderVB.NET.
Like all other .NET languages, VB.NET has complete support for objectoriented concepts.
EverythinginVB.NETisanobject,includingalloftheprimitivetypes(Short,Integer,Long,
String, Boolean, etc.) and userdefined types, events, and even assemblies. All objects
inheritsfromthebaseclassObject.
VB.NETisimplementedbyMicrosoft's.NETframework.Therefore,ithasfullaccesstoallthe
libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the
opensourcealternativeto.NET,notonlyunderWindows,butevenLinuxorMacOSX.
ThefollowingreasonsmakeVB.Netawidelyusedprofessionallanguage:
Modern,generalpurpose.
Objectoriented.
Componentoriented.
Easytolearn.
Structuredlanguage.
Itproducesefficientprograms.
Itcanbecompiledonavarietyofcomputerplatforms.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 1/158
23/09/2016 VB.NetQuickGuide
Partof.NetFramework.
StrongProgrammingFeaturesVB.Net
VB.Nethasnumerousstrongprogrammingfeaturesthatmakeitendearingtomultitudeof
programmersworldwide.Letusmentionsomeofthesefeatures:
BooleanConditions
AutomaticGarbageCollection
StandardLibrary
AssemblyVersioning
PropertiesandEvents
DelegatesandEventsManagement
EasytouseGenerics
Indexers
ConditionalCompilation
SimpleMultithreading
VB.NetEnvironment
Inthischapter,wewilldiscussthetoolsavailableforcreatingVB.Netapplications.
WehavealreadymentionedthatVB.Netispartof.Netframeworkandusedforwriting.Net
applications.ThereforebeforediscussingtheavailabletoolsforrunningaVB.Netprogram,let
usunderstandhowVB.Netrelatestothe.Netframework.
The.NetFramework
The.Netframeworkisarevolutionaryplatformthathelpsyoutowritethefollowingtypesof
applications:
Windowsapplications
Webapplications
Webservices
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 2/158
23/09/2016 VB.NetQuickGuide
The .Net framework applications are multiplatform applications. The framework has been
designedinsuchawaythatitcanbeusedfromanyofthefollowinglanguages:VisualBasic,
C#,C++,Jscript,andCOBOL,etc.
Alltheselanguagescanaccesstheframeworkaswellascommunicatewitheachother.
The .Net framework consists of an enormous library of codes used by the client languages
likeVB.Net.Theselanguagesuseobjectorientedmethodology.
Followingaresomeofthecomponentsofthe.Netframework:
CommonLanguageRuntime(CLR)
The.NetFrameworkClassLibrary
CommonLanguageSpecification
CommonTypeSystem
MetadataandAssemblies
WindowsForms
ASP.NetandASP.NetAJAX
ADO.Net
WindowsWorkflowFoundation(WF)
WindowsPresentationFoundation
WindowsCommunicationFoundation(WCF)
LINQ
Forthejobseachofthesecomponentsperform,pleaseseeASP.NetIntroduction , and
fordetailsofeachcomponent,pleaseconsultMicrosoft'sdocumentation.
IntegratedDevelopmentEnvironment(IDE)ForVB.Net
MicrosoftprovidesthefollowingdevelopmenttoolsforVB.Netprogramming:
VisualStudio2010(VS)
VisualBasic2010Express(VBE)
VisualWebDeveloper
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 3/158
23/09/2016 VB.NetQuickGuide
The last two are free. Using these tools, you can write all kinds of VB.Net programs from
simple commandline applications to more complex applications. Visual Basic Express and
VisualWebDeveloperExpresseditionaretrimmeddownversionsofVisualStudioandhas
thesamelookandfeel.TheyretainmostfeaturesofVisualStudio.Inthistutorial,wehave
used Visual Basic 2010 Express and Visual Web Developer (for the web programming
chapter).
You can download it from here . It gets automatically installed in your machine. Please
notethatyouneedanactiveinternetconnectionforinstallingtheexpressedition.
WritingVB.NetProgramsonLinuxorMacOS
Although the.NET Framework runs on the Windows operating system, there are some
alternativeversionsthatworkonotheroperatingsystems.Monoisanopensourceversion
ofthe.NETFrameworkwhichincludesaVisualBasiccompilerandrunsonseveraloperating
systems,includingvariousflavorsofLinuxandMacOS.ThemostrecentversionisVB2012.
ThestatedpurposeofMonoisnotonlytobeabletorunMicrosoft.NETapplicationscross
platform,butalsotobringbetterdevelopmenttoolstoLinuxdevelopers.Monocanberunon
many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris and
UNIX.
VB.NetProgramStructure
Before we study basic building blocks of the VB.Net programming language, let us look a
bareminimumVB.Netprogramstructuresothatwecantakeitasareferenceinupcoming
chapters.
VB.NetHelloWorldExample
AVB.Netprogrambasicallyconsistsofthefollowingparts:
Namespacedeclaration
Aclassormodule
Oneormoreprocedures
Variables
TheMainprocedure
Statements&Expressions
Comments
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 4/158
23/09/2016 VB.NetQuickGuide
Letuslookatasimplecodethatwouldprintthewords"HelloWorld":
ImportsSystem
ModuleModule1
'ThisprogramwilldisplayHelloWorld
SubMain()
Console.WriteLine("HelloWorld")
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Hello,World!
Letuslookvariouspartsoftheaboveprogram:
The first line of the program Imports System is used to include the System
namespaceintheprogram.
ThenextlinehasaModuledeclaration,themoduleModule1.VB.Netiscompletely
objectoriented,soeveryprogrammustcontainamoduleofaclassthatcontainsthe
dataandproceduresthatyourprogramuses.
Classes or Modules generally would contain more than one procedure. Procedures
containtheexecutablecode,orinotherwords,theydefinethebehavioroftheclass.
Aprocedurecouldbeanyofthefollowing:
Function
Sub
Operator
Get
Set
AddHandler
RemoveHandler
RaiseEvent
Thenextline('Thisprogram)willbeignoredbythecompilerandithasbeenputto
addadditionalcommentsintheprogram.
The next line defines the Main procedure, which is the entry point for all VB.Net
programs. The Main procedure states what the module or class will do when
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 5/158
23/09/2016 VB.NetQuickGuide
executed.
TheMainprocedurespecifiesitsbehaviorwiththestatement
Console.WriteLine("HelloWorld")
WriteLineisamethodoftheConsoleclassdefinedintheSystemnamespace.This
statementcausesthemessage"Hello,World!"tobedisplayedonthescreen.
The last line Console.ReadKey() is for the VS.NET Users. This will prevent the
screen from running and closing quickly when the program is launched from Visual
Studio.NET.
Compile&ExecuteVB.NetProgram:
IfyouareusingVisualStudio.NetIDE,takethefollowingsteps:
StartVisualStudio.
Onthemenubar,chooseFile,New,Project.
ChooseVisualBasicfromtemplates
ChooseConsoleApplication.
Specify a name and location for your project using the Browse button, and then
choosetheOKbutton.
ThenewprojectappearsinSolutionExplorer.
WritecodeintheCodeEditor.
ClicktheRunbuttonortheF5keytoruntheproject.ACommandPromptwindow
appearsthatcontainsthelineHelloWorld.
YoucancompileaVB.NetprogrambyusingthecommandlineinsteadoftheVisualStudio
IDE:
Openatexteditorandaddtheabovementionedcode.
Savethefileashelloworld.vb
Openthecommandprompttoolandgotothedirectorywhereyousavedthefile.
Typevbchelloworld.vbandpressentertocompileyourcode.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 6/158
23/09/2016 VB.NetQuickGuide
Iftherearenoerrorsinyourcodethecommandpromptwilltakeyoutothenextline
andwouldgeneratehelloworld.exeexecutablefile.
Next,typehelloworldtoexecuteyourprogram.
Youwillbeabletosee"HelloWorld"printedonthescreen.
VB.NetBasicSyntax
VB.Net is an objectoriented programming language. In ObjectOriented Programming
methodology,aprogramconsistsofvariousobjectsthatinteractwitheachotherbymeans
of actions. The actions that an object may take are called methods. Objects of the same
kindaresaidtohavethesametypeor,moreoften,aresaidtobeinthesameclass.
Object Objects have states and behaviors. Example: A dog has states color,
name, breed as well as behaviors wagging, barking, eating, etc. An object is an
instanceofaclass.
MethodsAmethodisbasicallyabehavior.Aclasscancontainmanymethods.It
is in methods where the logics are written, data is manipulated and all the actions
areexecuted.
InstantVariablesEachobjecthasitsuniquesetofinstantvariables.Anobject's
stateiscreatedbythevaluesassignedtotheseinstantvariables.
ARectangleClassinVB.Net
For example, let us consider a Rectangle object. It has attributes like length and width.
Dependinguponthedesign,itmayneedwaysforacceptingthevaluesoftheseattributes,
calculatingareaanddisplayingdetails.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on
thebasisofourobservationsinit:
ImportsSystem
PublicClassRectangle
PrivatelengthAsDouble
PrivatewidthAsDouble
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 7/158
23/09/2016 VB.NetQuickGuide
'Publicmethods
PublicSubAcceptDetails()
length=4.5
width=3.5
EndSub
PublicFunctionGetArea()AsDouble
GetArea=length*width
EndFunction
PublicSubDisplay()
Console.WriteLine("Length:{0}",length)
Console.WriteLine("Width:{0}",width)
Console.WriteLine("Area:{0}",GetArea())
EndSub
SharedSubMain()
DimrAsNewRectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Length:4.5
Width:3.5
Area:15.75
Inpreviouschapter,wecreatedaVisualBasicmodulethatheldthecode.SubMainindicates
the entry point of VB.Net program. Here, we are using Class that contains both code and
data.Youuseclassestocreateobjects.Forexample,inthecode,risaRectangleobject.
Anobjectisaninstanceofaclass:
DimrAsNewRectangle()
Aclassmayhavemembersthatcanbeaccessiblefromoutsideclass,ifsospecified.Data
membersarecalledfieldsandproceduremembersarecalledmethods.
Sharedmethodsorstaticmethodscanbeinvokedwithoutcreatinganobjectoftheclass.
Instancemethodsareinvokedthroughanobjectoftheclass:
SharedSubMain()
DimrAsNewRectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
EndSub
Identifiers
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 8/158
23/09/2016 VB.NetQuickGuide
Anidentifierisanameusedtoidentifyaclass,variable,function,oranyotheruserdefined
item.ThebasicrulesfornamingclassesinVB.Netareasfollows:
A name must begin with a letter that could be followed by a sequence of letters,
digits(09)orunderscore.Thefirstcharacterinanidentifiercannotbeadigit.
Itmustnotcontainanyembeddedspaceorsymbollike?+!@#%^&*()[]{
}.:"'/and\.However,anunderscore(_)canbeused.
Itshouldnotbeareservedkeyword.
VB.NetKeywords
ThefollowingtableliststheVB.Netreservedkeywords:
Namespace
Inheritable Overridable
Handler
VB.NetDataTypes
Datatypesrefertoanextensivesystemusedfordeclaringvariablesorfunctionsofdifferent
types.Thetypeofavariabledetermineshowmuchspaceitoccupiesinstorageandhowthe
bitpatternstoredisinterpreted.
DataTypesAvailableinVB.Net
VB.Net provides a wide range of data types. The following table shows all the data types
available:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 10/158
23/09/2016 VB.NetQuickGuide
4.94065645841246544E324 through
1.79769313486231570E+308,forpositivevalues
8 bytes on 64
bitplatform
Example
Thefollowingexampledemonstratesuseofsomeofthetypes:
ModuleDataTypes
SubMain()
DimbAsByte
DimnAsInteger
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 11/158
23/09/2016 VB.NetQuickGuide
DimsiAsSingle
DimdAsDouble
DimdaAsDate
DimcAsChar
DimsAsString
DimblAsBoolean
b=1
n=1234567
si=0.12345678901234566
d=0.12345678901234566
da=Today
c="U"c
s="Me"
IfScriptEngine="VB"Then
bl=True
Else
bl=False
EndIf
IfblThen
'theoathtaking
Console.Write(c&"and,"&s&vbCrLf)
Console.WriteLine("declaringonthedayof:{0}",da)
Console.WriteLine("WewilllearnVB.Netseriously")
Console.WriteLine("Letsseewhathappenstothefloatingpointvariables:")
Console.WriteLine("TheSingle:{0},TheDouble:{1}",si,d)
EndIf
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Uand,Me
declaringonthedayof:12/4/201212:00:00PM
WewilllearnVB.Netseriously
Letsseewhathappenstothefloatingpointvariables:
TheSingle:0.1234568,TheDouble:0.123456789012346
TheTypeConversionFunctionsinVB.Net
VB.Netprovidesthefollowinginlinetypeconversionfunctions:
S.N Functions&Description
1 CBool(expression)
ConvertstheexpressiontoBooleandatatype.
2 CByte(expression)
ConvertstheexpressiontoBytedatatype.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 12/158
23/09/2016 VB.NetQuickGuide
3 CChar(expression)
ConvertstheexpressiontoChardatatype.
4 CDate(expression)
ConvertstheexpressiontoDatedatatype
5 CDbl(expression)
ConvertstheexpressiontoDoubledatatype.
6 CDec(expression)
ConvertstheexpressiontoDecimaldatatype.
7 CInt(expression)
ConvertstheexpressiontoIntegerdatatype.
8 CLng(expression)
ConvertstheexpressiontoLongdatatype.
9 CObj(expression)
ConvertstheexpressiontoObjecttype.
10 CSByte(expression)
ConvertstheexpressiontoSBytedatatype.
11 CShort(expression)
ConvertstheexpressiontoShortdatatype.
12 CSng(expression)
ConvertstheexpressiontoSingledatatype.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 13/158
23/09/2016 VB.NetQuickGuide
13 CStr(expression)
ConvertstheexpressiontoStringdatatype.
14 CUInt(expression)
ConvertstheexpressiontoUIntdatatype.
15 CULng(expression)
ConvertstheexpressiontoULngdatatype.
16 CUShort(expression)
ConvertstheexpressiontoUShortdatatype.
Example:
Thefollowingexampledemonstratessomeofthesefunctions:
ModuleDataTypes
SubMain()
DimnAsInteger
DimdaAsDate
DimblAsBoolean=True
n=1234567
da=Today
Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
True
1
True
12/4/2012
1
1
VB.NetVariables
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 14/158
23/09/2016 VB.NetQuickGuide
Avariableisnothingbutanamegiventoastorageareathatourprogramscanmanipulate.
Each variable in VB.Net has a specific type, which determines the size and layout of the
variable'smemorytherangeofvaluesthatcanbestoredwithinthatmemoryandtheset
ofoperationsthatcanbeappliedtothevariable.
Wehavealreadydiscussedvariousdatatypes.ThebasicvaluetypesprovidedinVB.Netcan
becategorizedas:
Type Example
Integraltypes SByte,Byte,Short,UShort,Integer,UInteger,Long,ULongandChar
Floatingpointtypes SingleandDouble
Decimaltypes Decimal
Booleantypes TrueorFalsevalues,asassigned
Datetypes Date
VB.NetalsoallowsdefiningothervaluetypesofvariablelikeEnumandreferencetypesof
variableslikeClass.WewilldiscussdatetypesandClassesinsubsequentchapters.
VariableDeclarationinVB.Net
TheDim statement is used for variable declaration and storage allocation for one or more
variables.TheDimstatementisusedatmodule,class,structure,procedureorblocklevel.
SyntaxforvariabledeclarationinVB.Netis:
[<attributelist>][accessmodifier][[Shared][Shadows]|[Static]]
[ReadOnly]Dim[WithEvents]variablelist
Where,
attributelistisalistofattributesthatapplytothevariable.Optional.
accessmodifierdefinestheaccesslevelsofthevariables,ithasvaluesasPublic,
Protected,Friend,ProtectedFriendandPrivate.Optional.
Shareddeclaresasharedvariable,whichisnotassociatedwithanyspecificinstance
ofaclassorstructure,ratheravailabletoalltheinstancesoftheclassorstructure.
Optional.
Shadows indicate that the variable redeclares and hides an identically named
element,orsetofoverloadedelements,inabaseclass.Optional.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 15/158
23/09/2016 VB.NetQuickGuide
Static indicates that the variable will retain its value, even when the after
terminationoftheprocedureinwhichitisdeclared.Optional.
ReadOnlymeansthevariablecanberead,butnotwritten.Optional.
WithEvents specifies that the variable is used to respond to events raised by the
instanceassignedtothevariable.Optional.
Variablelistprovidesthelistofvariablesdeclared.
Eachvariableinthevariablelisthasthefollowingsyntaxandparts:
variablename[([boundslist])][As[New]datatype][=initializer]
Where,
variablename:isthenameofthevariable
New:optional.ItcreatesanewinstanceoftheclasswhentheDimstatementruns.
datatype:RequiredifOptionStrictisOn.Itspecifiesthedatatypeofthevariable.
Somevalidvariabledeclarationsalongwiththeirdefinitionareshownhere:
DimStudentIDAsInteger
DimStudentNameAsString
DimSalaryAsDouble
Dimcount1,count2AsInteger
DimstatusAsBoolean
DimexitButtonAsNewSystem.Windows.Forms.Button
DimlastTime,nextTimeAsDate
VariableInitializationinVB.Net
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression.Thegeneralformofinitializationis:
variable_name=value;
forexample,
DimpiAsDouble
pi=3.14159
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 16/158
23/09/2016 VB.NetQuickGuide
Youcaninitializeavariableatthetimeofdeclarationasfollows:
DimStudentIDAsInteger=100
DimStudentNameAsString="BillSmith"
Example
Trythefollowingexamplewhichmakesuseofvarioustypesofvariables:
ModulevariablesNdataypes
SubMain()
DimaAsShort
DimbAsInteger
DimcAsDouble
a=10
b=20
c=a+b
Console.WriteLine("a={0},b={1},c={2}",a,b,c)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
a=10,b=20,c=30
AcceptingValuesfromUser
The Console class in the System namespace provides a function ReadLine for accepting
inputfromtheuserandstoreitintoavariable.Forexample,
DimmessageAsString
message=Console.ReadLine
Thefollowingexampledemonstratesit:
ModulevariablesNdataypes
SubMain()
DimmessageAsString
Console.Write("Entermessage:")
message=Console.ReadLine
Console.WriteLine()
Console.WriteLine("YourMessage:{0}",message)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult(assumethe
userinputsHelloWorld):
Entermessage:HelloWorld
YourMessage:HelloWorld
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 17/158
23/09/2016 VB.NetQuickGuide
LvaluesandRvalues
Therearetwokindsofexpressions:
lvalue:Anexpressionthatisanlvaluemayappearaseitherthelefthandorright
handsideofanassignment.
rvalue:Anexpressionthatisanrvaluemayappearontherightbutnotlefthand
sideofanassignment.
Variables are lvalues and so may appear on the lefthand side of an assignment. Numeric
literals are rvalues and so may not be assigned and can not appear on the lefthand side.
Followingisavalidstatement:
DimgAsInteger=20
Butfollowingisnotavalidstatementandwouldgeneratecompiletimeerror:
20=g
VB.NetConstantsandEnumerations
The constants refer to fixed values that the program may not alter during its execution.
Thesefixedvaluesarealsocalledliterals.
Constantscanbeofanyofthebasicdatatypeslikeanintegerconstant,afloatingconstant,
acharacterconstant,orastringliteral.Therearealsoenumerationconstantsaswell.
The constants are treated just like regular variables except that their values cannot be
modifiedaftertheirdefinition.
Anenumerationisasetofnamedintegerconstants.
DeclaringConstants
InVB.Net,constantsaredeclaredusingtheConststatement.TheConststatementisused
atmodule,class,structure,procedure,orblocklevelforuseinplaceofliteralvalues.
ThesyntaxfortheConststatementis:
[<attributelist>][accessmodifier][Shadows]
Constconstantlist
Where,
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 18/158
23/09/2016 VB.NetQuickGuide
attributelist: specifies the list of attributes applied to the constants you can
providemultipleattributesseparatedbycommas.Optional.
accessmodifier:specifieswhichcodecanaccesstheseconstants.Optional.Values
canbeeitherofthe:Public,Protected,Friend,ProtectedFriend,orPrivate.
Shadows:thismakestheconstanthideaprogrammingelementofidenticalname
inabaseclass.Optional.
Constantlist:givesthelistofnamesofconstantsdeclared.Required.
Where,eachconstantnamehasthefollowingsyntaxandparts:
constantname[Asdatatype]=initializer
constantname:specifiesthenameoftheconstant
datatype:specifiesthedatatypeoftheconstant
initializer:specifiesthevalueassignedtotheconstant
Forexample,
'Thefollowingstatementsdeclareconstants.
ConstmaxvalAsLong=4999
PublicConstmessageAsString="HELLO"
PrivateConstpiValueAsDouble=3.1415
Example
Thefollowingexampledemonstratesdeclarationanduseofaconstantvalue:
ModuleconstantsNenum
SubMain()
ConstPI=3.14149
Dimradius,areaAsSingle
radius=7
area=PI*radius*radius
Console.WriteLine("Area="&Str(area))
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Area=153.933
PrintandDisplayConstantsinVB.Net
VB.Netprovidesthefollowingprintanddisplayconstants:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 19/158
23/09/2016 VB.NetQuickGuide
Constant Description
vbCrLf Carriagereturn/linefeedcharactercombination.
vbCr Carriagereturncharacter.
vbLf Linefeedcharacter.
vbNewLine Newlinecharacter.
vbNullChar Nullcharacter.
vbNullString Notthesameasazerolengthstring("")usedforcallingexternal
procedures.
vbObjectError Errornumber.Userdefinederrornumbersshouldbegreaterthanthis
value.Forexample:
Err.Raise(Number)=vbObjectError+1000
vbTab Tabcharacter.
vbBack Backspacecharacter.
DeclaringEnumerations
AnenumeratedtypeisdeclaredusingtheEnumstatement.TheEnumstatementdeclares
anenumerationanddefinesthevaluesofitsmembers.TheEnumstatementcanbeusedat
themodule,class,structure,procedure,orblocklevel.
ThesyntaxfortheEnumstatementisasfollows:
[<attributelist>][accessmodifier][Shadows]
Enumenumerationname[Asdatatype]
memberlist
EndEnum
Where,
attributelist:referstothelistofattributesappliedtothevariable.Optional.
enumerationname:nameoftheenumeration.Required
datatype:specifiesthedatatypeoftheenumerationandallitsmembers.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 20/158
23/09/2016 VB.NetQuickGuide
Eachmemberinthememberlisthasthefollowingsyntaxandparts:
[<attributelist>]membername[=initializer]
Where,
name:specifiesthenameofthemember.Required.
initializer:valueassignedtotheenumerationmember.Optional.
Forexample,
EnumColors
red=1
orange=2
yellow=3
green=4
azure=5
blue=6
violet=7
EndEnum
Example
ThefollowingexampledemonstratesdeclarationanduseoftheEnumvariableColors:
ModuleconstantsNenum
EnumColors
red=1
orange=2
yellow=3
green=4
azure=5
blue=6
violet=7
EndEnum
SubMain()
Console.WriteLine("TheColorRedis:"&Colors.red)
Console.WriteLine("TheColorYellowis:"&Colors.yellow)
Console.WriteLine("TheColorBlueis:"&Colors.blue)
Console.WriteLine("TheColorGreenis:"&Colors.green)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
TheColorRedis:1
TheColorYellowis:3
TheColorBlueis:6
TheColorGreenis:4
VB.NetModifiers
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 21/158
23/09/2016 VB.NetQuickGuide
VB.NetModifiers
The modifiers are keywords added with any programming element to give some especial
emphasisonhowtheprogrammingelementwillbehaveorwillbeaccessedintheprogram
Forexample,theaccessmodifiers:Public,Private,Protected,Friend,ProtectedFriend,etc.,
indicatetheaccesslevelofaprogrammingelementlikeavariable,constant,enumerationor
aclass.
ListofAvailableModifiersinVB.Net
ThefollowingtableprovidesthecompletelistofVB.Netmodifiers:
1 Ansi SpecifiesthatVisualBasicshouldmarshalallstringstoAmerican
NationalStandardsInstitute(ANSI)valuesregardlessofthe
nameoftheexternalprocedurebeingdeclared.
2 Assembly Specifiesthatanattributeatthebeginningofasourcefile
appliestotheentireassembly.
3 Async Indicatesthatthemethodorlambdaexpressionthatitmodifies
isasynchronous.Suchmethodsarereferredtoasasyncmethods.
Thecallerofanasyncmethodcanresumeitsworkwithout
waitingfortheasyncmethodtofinish.
4 Auto ThecharsetmodifierpartintheDeclarestatementsuppliesthe
charactersetinformationformarshalingstringsduringacallto
theexternalprocedure.ItalsoaffectshowVisualBasicsearches
theexternalfilefortheexternalprocedurename.TheAuto
modifierspecifiesthatVisualBasicshouldmarshalstrings
accordingto.NETFrameworkrules.
5 ByRef Specifiesthatanargumentispassedbyreference,i.e.,thecalled
procedurecanchangethevalueofavariableunderlyingthe
argumentinthecallingcode.Itisusedunderthecontextsof:
DeclareStatement
FunctionStatement
SubStatement
6 ByVal Specifiesthatanargumentispassedinsuchawaythatthe
calledprocedureorpropertycannotchangethevalueofa
variableunderlyingtheargumentinthecallingcode.Itisused
underthecontextsof:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 22/158
23/09/2016 VB.NetQuickGuide
DeclareStatement
FunctionStatement
OperatorStatement
PropertyStatement
SubStatement
7 Default Identifiesapropertyasthedefaultpropertyofitsclass,
structure,orinterface.
Friendaccessisoftenthepreferredlevelforanapplication's
programming elements, and Friend is the default access
levelofaninterface,amodule,aclass,orastructure.
9 In Itisusedingenericinterfacesanddelegates.
10 Iterator SpecifiesthatafunctionorGetaccessorisaniterator.An
iteratorperformsacustomiterationoveracollection.
11 Key TheKeykeywordenablesyoutospecifybehaviorforpropertiesof
anonymoustypes.
12 Module Specifiesthatanattributeatthebeginningofasourcefile
appliestothecurrentassemblymodule.Itisnotsameasthe
Modulestatement.
13 MustInherit Specifiesthataclasscanbeusedonlyasabaseclassandthat
youcannotcreateanobjectdirectlyfromit.
14 MustOverride Specifiesthatapropertyorprocedureisnotimplementedinthis
classandmustbeoverriddeninaderivedclassbeforeitcanbe
used.
15 Narrowing Indicatesthataconversionoperator(CType)convertsaclassor
structuretoatypethatmightnotbeabletoholdsomeofthe
possiblevaluesoftheoriginalclassorstructure.
16 NotInheritable Specifiesthataclasscannotbeusedasabaseclass.
17 NotOverridable Specifiesthatapropertyorprocedurecannotbeoverriddenina
derivedclass.
18 Optional Specifiesthataprocedureargumentcanbeomittedwhenthe
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 23/158
23/09/2016 VB.NetQuickGuide
procedureiscalled.
19 Out Forgenerictypeparameters,theOutkeywordspecifiesthatthe
typeiscovariant.
20 Overloads Specifiesthatapropertyorprocedureredeclaresoneormore
existingpropertiesorprocedureswiththesamename.
21 Overridable Specifiesthatapropertyorprocedurecanbeoverriddenbyan
identicallynamedpropertyorprocedureinaderivedclass.
22 Overrides Specifiesthatapropertyorprocedureoverridesanidentically
namedpropertyorprocedureinheritedfromabaseclass.
23 ParamArray ParamArrayallowsyoutopassanarbitrarynumberofarguments
totheprocedure.AParamArrayparameterisalwaysdeclared
usingByVal.
24 Partial Indicatesthataclassorstructuredeclarationisapartial
definitionoftheclassorstructure.
25 Private Specifiesthatoneormoredeclaredprogrammingelementsare
accessibleonlyfromwithintheirdeclarationcontext,including
fromwithinanycontainedtypes.
26 Protected Specifiesthatoneormoredeclaredprogrammingelementsare
accessibleonlyfromwithintheirownclassorfromaderived
class.
27 Public Specifiesthatoneormoredeclaredprogrammingelementshave
noaccessrestrictions.
28 ReadOnly Specifiesthatavariableorpropertycanbereadbutnotwritten.
29 Shadows Specifiesthatadeclaredprogrammingelementredeclaresand
hidesanidenticallynamedelement,orsetofoverloaded
elements,inabaseclass.
30 Shared Specifiesthatoneormoredeclaredprogrammingelementsare
associatedwithaclassorstructureatlarge,andnotwitha
specificinstanceoftheclassorstructure.
31 Static Specifiesthatoneormoredeclaredlocalvariablesaretocontinue
toexistandretaintheirlatestvaluesafterterminationofthe
procedureinwhichtheyaredeclared.
32 Unicode SpecifiesthatVisualBasicshouldmarshalallstringstoUnicode
valuesregardlessofthenameoftheexternalprocedurebeing
declared.
33 Widening Indicatesthataconversionoperator(CType)convertsaclassor
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 24/158
23/09/2016 VB.NetQuickGuide
structuretoatypethatcanholdallpossiblevaluesoftheoriginal
classorstructure.
34 WithEvents Specifiesthatoneormoredeclaredmembervariablesrefertoan
instanceofaclassthatcanraiseevents.
35 WriteOnly Specifiesthatapropertycanbewrittenbutnotread.
VB.NetStatements
AstatementisacompleteinstructioninVisualBasicprograms.Itmaycontainkeywords,
operators,variables,literalvalues,constantsandexpressions.
Statementscouldbecategorizedas:
DeclarationStatements
Thedeclarationstatementsareusedtonameanddefineprocedures,variables,properties,
arrays, and constants. When you declare a programming element, you can also define its
datatype,accesslevel,andscope.
The programming elements you may declare include variables, constants, enumerations,
classes,structures,modules,interfaces,procedures,procedureparameters,functionreturns,
externalprocedurereferences,operators,properties,events,anddelegates.
FollowingarethedeclarationstatementsinVB.Net:
1 DimStatement DimnumberAsInteger
DimquantityAsInteger=100
Declares and allocates storage space for DimmessageAsString="Hello!"
oneormorevariables.
2 ConstStatement ConstmaximumAsLong=1000
Declaresanddefinesoneormoreconstants. ConstnaturalLogBaseAsObject
=CDec(2.7182818284)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 25/158
23/09/2016 VB.NetQuickGuide
3 EnumStatement EnumCoffeeMugSize
Declaresanenumerationanddefinesthe Jumbo
valuesofitsmembers. ExtraLarge
Large
Medium
Small
EndEnum
4 ClassStatement ClassBox
PubliclengthAsDouble
PublicbreadthAsDouble
Declares the name of a class and
PublicheightAsDouble
introduces the definition of the variables, EndClass
properties,events,andproceduresthatthe
classcomprises.
5 StructureStatement StructureBox
PubliclengthAsDouble
PublicbreadthAsDouble
Declares the name of a structure and
PublicheightAsDouble
introduces the definition of the variables, EndStructure
properties,events,andproceduresthatthe
structurecomprises.
6 ModuleStatement PublicModulemyModule
SubMain()
DimuserAsString=
Declares the name of a module and
InputBox("Whatisyourname?")
introduces the definition of the variables, MsgBox("Usernameis"&user)
EndSub
properties,events,andproceduresthatthe
EndModule
modulecomprises.
7 InterfaceStatement PublicInterfaceMyInterface
SubdoSomething()
EndInterface
Declaresthenameofaninterfaceand
introducesthedefinitionsofthemembersthat
theinterfacecomprises.
8 FunctionStatement FunctionmyFunction
(ByValnAsInteger)AsDouble
Return5.87*n
Declares the name, parameters, and code
EndFunction
thatdefineaFunctionprocedure.
9 SubStatement SubmySub(ByValsAsString)
Return
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 26/158
23/09/2016 VB.NetQuickGuide
thatdefineaSubprocedure.
10 DeclareStatement DeclareFunctiongetUserName
Lib"advapi32.dll"
Alias"GetUserNameA"
Declares a reference to a procedure
(
implementedinanexternalfile. ByVallpBufferAsString,
ByRefnSizeAsInteger)AsInteger
11 OperatorStatement PublicSharedOperator+
(ByValxAsobj,ByValyAsobj)As
obj
Declares the operator symbol, operands,
DimrAsNewobj
andcodethatdefineanoperatorprocedure 'implementioncodeforr=x+y
Returnr
onaclassorstructure.
EndOperator
12 PropertyStatement ReadOnlyPropertyquote()AsString
Get
ReturnquoteString
Declares the name of a property, and the
EndGet
property procedures used to store and EndProperty
retrievethevalueoftheproperty.
13 EventStatement PublicEventFinished()
Declaresauserdefinedevent.
14 DelegateStatement DelegateFunctionMathOperator(
ByValxAsDouble,
ByValyAsDouble
Usedtodeclareadelegate.
)AsDouble
ExecutableStatements
Anexecutablestatementperformsanaction.Statementscallingaprocedure,branchingto
anotherplaceinthecode,loopingthroughseveralstatements,orevaluatinganexpression
are executable statements. An assignment statement is a special case of an executable
statement.
Example
Thefollowingexampledemonstratesadecisionmakingstatement:
Moduledecisions
SubMain()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 27/158
23/09/2016 VB.NetQuickGuide
'localvariabledefinition'
DimaAsInteger=10
'checkthebooleanconditionusingifstatement'
If(a<20)Then
'ifconditionistruethenprintthefollowing'
Console.WriteLine("aislessthan20")
EndIf
Console.WriteLine("valueofais:{0}",a)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
aislessthan20;
valueofais:10
VB.NetDirectives
The VB.Net compiler directives give instructions to the compiler to preprocess the
informationbeforeactualcompilationstarts.
All these directives begin with #, and only whitespace characters may appear before a
directiveonaline.Thesedirectivesarenotstatements.
VB.Net compiler does not have a separate preprocessor however, the directives are
processed as if there was one. In VB.Net, the compiler directives are used to help in
conditionalcompilation.UnlikeCandC++directives,theyarenotusedtocreatemacros.
CompilerDirectivesinVB.Net
VB.Netprovidesthefollowingsetofcompilerdirectives:
The#ConstDirective
The#ExternalSourceDirective
The#If...Then...#ElseDirectives
The#RegionDirective
The#ConstDirective
Thisdirectivedefinesconditionalcompilerconstants.Syntaxforthisdirectiveis:
#Constconstname=expression
Where,
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 28/158
23/09/2016 VB.NetQuickGuide
constname:specifiesthenameoftheconstant.Required.
Forexample,
#Conststate="WESTBENGAL"
Example
Thefollowingcodedemonstratesahypotheticaluseofthedirective:
Modulemydirectives
#Constage=True
SubMain()
#IfageThen
Console.WriteLine("YouarewelcometotheRoboticsClub")
#EndIf
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
YouarewelcometotheRoboticsClub
The#ExternalSourceDirective
Thisdirectiveisusedforindicatingamappingbetweenspecificlinesofsourcecodeandtext
external to the source. It is used only by the compiler and the debugger has no effect on
codecompilation.
Thisdirectiveallowsincludingexternalcodefromanexternalcodefileintoasourcecodefile.
Syntaxforthisdirectiveis:
#ExternalSource(StringLiteral,IntLiteral)
[LogicalLine]
#EndExternalSource
Theparametersof#ExternalSourcedirectivearethepathofexternalfile,linenumberofthe
firstline,andthelinewheretheerroroccurred.
Example
Thefollowingcodedemonstratesahypotheticaluseofthedirective:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 29/158
23/09/2016 VB.NetQuickGuide
Modulemydirectives
PublicClassExternalSourceTester
SubTestExternalSource()
#ExternalSource("c:\vbprogs\directives.vb",5)
Console.WriteLine("ThisisExternalCode.")
#EndExternalSource
EndSub
EndClass
SubMain()
DimtAsNewExternalSourceTester()
t.TestExternalSource()
Console.WriteLine("InMain.")
Console.ReadKey()
EndSub
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
ThisisExternalCode.
InMain.
The#If...Then...#ElseDirectives
ThisdirectiveconditionallycompilesselectedblocksofVisualBasiccode.
Syntaxforthisdirectiveis:
#IfexpressionThen
statements
[#ElseIfexpressionThen
[statements]
...
#ElseIfexpressionThen
[statements]]
[#Else
[statements]]
#EndIf
Forexample,
#ConstTargetOS="Linux"
#IfTargetOS="Windows7"Then
'Windows7specificcode
#ElseIfTargetOS="WinXP"Then
'WindowsXPspecificcode
#Else
'CodeforotherOS
#Endif
Example
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 30/158
23/09/2016 VB.NetQuickGuide
Thefollowingcodedemonstratesahypotheticaluseofthedirective:
Modulemydirectives
#ConstclassCode=8
SubMain()
#IfclassCode=7Then
Console.WriteLine("ExamQuestionsforClassVII")
#ElseIfclassCode=8Then
Console.WriteLine("ExamQuestionsforClassVIII")
#Else
Console.WriteLine("ExamQuestionsforHigherClasses")
#EndIf
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
ExamQuestionsforClassVIII
The#RegionDirective
ThisdirectivehelpsincollapsingandhidingsectionsofcodeinVisualBasicfiles.
Syntaxforthisdirectiveis:
#Region"identifier_string"
#EndRegion
Forexample,
#Region"StatsFunctions"
'InsertcodefortheStatisticalfunctionshere.
#EndRegion
VB.NetOperators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.VB.Netisrichinbuiltinoperatorsandprovidesfollowingtypesofcommonly
usedoperators:
ArithmeticOperators
ComparisonOperators
Logical/BitwiseOperators
BitShiftOperators
AssignmentOperators
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 31/158
23/09/2016 VB.NetQuickGuide
MiscellaneousOperators
Thistutorialwillexplainthemostcommonlyusedoperators.
ArithmeticOperators
FollowingtableshowsallthearithmeticoperatorssupportedbyVB.Net.AssumevariableA
holds2andvariableBholds7,then:
ShowExamples
^ Raisesoneoperandtothepowerofanother B^Awillgive49
+ Addstwooperands A+Bwillgive9
Subtractssecondoperandfromthefirst ABwillgive5
* Multipliesbothoperands A*Bwillgive14
/ Dividesoneoperandbyanotherandreturnsa B/Awillgive3.5
floatingpointresult
\ Dividesoneoperandbyanotherandreturnsan B\Awillgive3
integerresult
ComparisonOperators
FollowingtableshowsallthecomparisonoperatorssupportedbyVB.Net.AssumevariableA
holds10andvariableBholds20,then:
ShowExamples
= Checksifthevaluesoftwooperandsareequalor (A=B)isnottrue.
notifyes,thenconditionbecomestrue.
thevalueofrightoperandifyes,thencondition
becomestrue.
Apartfromtheabove,VB.Netprovidesthreemorecomparisonoperators,whichwewillbe
usinginforthcomingchaptershowever,wegiveabriefdescriptionhere.
IsNotOperatorItalsocomparestwoobjectreferencevariablesanddeterminesif
twoobjectreferencesrefertodifferentobjects.Ifobject1andobject2bothreferto
theexactsameobjectinstance,resultisFalseotherwise,resultisTrue.
LikeOperatorItcomparesastringagainstapattern.
Logical/BitwiseOperators
FollowingtableshowsallthelogicaloperatorssupportedbyVB.Net.AssumevariableAholds
BooleanvalueTrueandvariableBholdsBooleanvalueFalse,then:
ShowExamples
Or ItisthelogicalaswellasbitwiseORoperator.If (AOrB)isTrue.
anyofthetwooperandsistrue,thencondition
becomestrue.Thisoperatordoesnotperform
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 33/158
23/09/2016 VB.NetQuickGuide
shortcircuiting,i.e.,itevaluatesboththe
expressions.
IsFalse ItdetermineswhetheranexpressionisFalse.
IsTrue ItdetermineswhetheranexpressionisTrue.
BitShiftOperators
We have already discussed the bitwise operators. The bit shift operators perform the shift
operationsonbinaryvalues.Beforecomingintothebitshiftoperators,letusunderstandthe
bitoperations.
Bitwise operators work on bits and perform bitbybit operations. The truth tables for &, |,
and^areasfollows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
AssumeifA=60andB=13nowinbinaryformattheywillbeasfollows:
A=00111100
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 34/158
23/09/2016 VB.NetQuickGuide
B=00001101
A&B=00001100
A|B=00111101
A^B=00110001
~A=11000011
WehaveseenthattheBitwiseoperatorssupportedbyVB.NetareAnd,Or,XorandNot.The
Bitshiftoperatorsare>>and<<forleftshiftandrightshift,respectively.
AssumethatthevariableAholds60andvariableBholds13,then:
ShowExamples
Or BinaryOROperatorcopiesabitifitexistsineither (AOrB)willgive61,whichis
operand. 00111101
AssignmentOperators
TherearefollowingassignmentoperatorssupportedbyVB.Net:
ShowExamples
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 35/158
23/09/2016 VB.NetQuickGuide
= Simpleassignmentoperator,Assignsvaluesfrom C=A+Bwillassignvalueof
rightsideoperandstoleftsideoperand A+BintoC
+= AddANDassignmentoperator,Itaddsright C+=AisequivalenttoC=C
operandtotheleftoperandandassignstheresult +A
toleftoperand
= SubtractANDassignmentoperator,Itsubtracts C=AisequivalenttoC=C
rightoperandfromtheleftoperandandassignsthe A
resulttoleftoperand
*= MultiplyANDassignmentoperator,Itmultiplies C*=AisequivalenttoC=C
rightoperandwiththeleftoperandandassignsthe *A
resulttoleftoperand
/= DivideANDassignmentoperator,Itdividesleft C/=AisequivalenttoC=C
operandwiththerightoperandandassignsthe /A
resulttoleftoperand(floatingpointdivision)
\= DivideANDassignmentoperator,Itdividesleft C\=AisequivalenttoC=C
operandwiththerightoperandandassignsthe \A
resulttoleftoperand(Integerdivision)
^= Exponentiationandassignmentoperator.Itraises C^=AisequivalenttoC=C
theleftoperandtothepoweroftherightoperand ^A
andassignstheresulttoleftoperand.
MiscellaneousOperators
TherearefewotherimportantoperatorssupportedbyVB.Net.
ShowExamples
AddressOf Returnstheaddressofaprocedure.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 36/158
23/09/2016 VB.NetQuickGuide
AddHandlerButton1.Click,
AddressOfButton1_Click
Await Itisappliedtoanoperandinan
asynchronousmethodorlambdaexpression DimresultAsres
tosuspendexecutionofthemethoduntil =Await
AsyncMethodThatReturnsResult()
theawaitedtaskcompletes.
AwaitAsyncMethod()
If Itusesshortcircuitevaluationto Dimnum=5
conditionallyreturnoneoftwovalues.The Console.WriteLine(If(num>=0,
Ifoperatorcanbecalledwiththree "Positive","Negative"))
argumentsorwithtwoarguments.
OperatorsPrecedenceinVB.Net
Operatorprecedencedeterminesthegroupingoftermsinanexpression.Thisaffectshowan
expressionisevaluated.Certainoperatorshavehigherprecedencethanothersforexample,
themultiplicationoperatorhashigherprecedencethantheadditionoperator:
Forexample,x=7+3*2here,xisassigned13,not20becauseoperator*hashigher
precedencethan+,soitfirstgetsmultipliedwith3*2andthenaddsinto7.
Here,operatorswiththehighestprecedenceappearatthetopofthetable,thosewiththe
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluatedfirst.
ShowExamples
Operator Precedence
Await Highest
Exponentiation(^)
Unaryidentityandnegation(+,)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 37/158
23/09/2016 VB.NetQuickGuide
Multiplicationandfloatingpointdivision(*,/)
Integerdivision(\)
Modulusarithmetic(Mod)
Additionandsubtraction(+,)
Arithmeticbitshift(<<,>>)
Allcomparisonoperators(=,<>,<,<=,>,>=,Is,
IsNot,Like,TypeOf...Is)
Negation(Not)
Conjunction(And,AndAlso)
Inclusivedisjunction(Or,OrElse)
Exclusivedisjunction(Xor) Lowest
VB.NetDecisionMaking
Decisionmakingstructuresrequirethattheprogrammerspecifyoneormoreconditionsto
be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executediftheconditionisdeterminedtobefalse.
Following is the general form of a typical decision making structure found in most of the
programminglanguages:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 38/158
23/09/2016 VB.NetQuickGuide
VB.Netprovidesthefollowingtypesofdecisionmakingstatements.Clickthefollowinglinks
tochecktheirdetails.
Statement Description
If...Thenstatement AnIf...Thenstatementconsistsofabooleanexpression
followedbyoneormorestatements.
If...Then...Elsestatement AnIf...ThenstatementcanbefollowedbyanoptionalElse
statement,whichexecuteswhenthebooleanexpressionis
false.
nestedIfstatements YoucanuseoneIforElseifstatementinsideanotherIfor
Elseifstatement(s).
SelectCasestatement ASelectCasestatementallowsavariabletobetestedfor
equalityagainstalistofvalues.
nestedSelectCase Youcanuseoneselectcasestatementinsideanotherselect
statements casestatement(s).
VB.NetLoops
There may be a situation when you need to execute a block of code several number of
times.Ingeneral,statementsareexecutedsequentially:Thefirststatementinafunctionis
executedfirst,followedbythesecond,andsoon.
Programming languages provide various control structures that allow for more complicated
executionpaths.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 39/158
23/09/2016 VB.NetQuickGuide
VB.Netprovidesfollowingtypesofloopstohandleloopingrequirements.Clickthefollowing
linkstochecktheirdetails.
LoopType Description
DoLoop ItrepeatstheenclosedblockofstatementswhileaBoolean
conditionisTrueoruntiltheconditionbecomesTrue.Itcouldbe
terminatedatanytimewiththeExitDostatement.
For...Next Itrepeatsagroupofstatementsaspecifiednumberoftimesand
aloopindexcountsthenumberofloopiterationsastheloop
executes.
ForEach...Next Itrepeatsagroupofstatementsforeachelementinacollection.
Thisloopisusedforaccessingandmanipulatingallelementsinan
arrayoraVB.Netcollection.
While...EndWhile Itexecutesaseriesofstatementsaslongasagivenconditionis
True.
With...EndWith Itisnotexactlyaloopingconstruct.Itexecutesaseriesof
statementsthatrepeatedlyrefertoasingleobjectorstructure.
Nestedloops YoucanuseoneormoreloopsinsideanyanotherWhile,FororDo
loop.
LoopControlStatements:
Loopcontrolstatementschangeexecutionfromitsnormalsequence.Whenexecutionleaves
ascope,allautomaticobjectsthatwerecreatedinthatscopearedestroyed.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 40/158
23/09/2016 VB.NetQuickGuide
VB.Net provides the following control statements. Click the following links to check their
details.
ControlStatement Description
Exitstatement Terminatesthelooporselectcasestatementandtransfers
executiontothestatementimmediatelyfollowingtheloopor
selectcase.
Continuestatement Causesthelooptoskiptheremainderofitsbodyandimmediately
retestitsconditionpriortoreiterating.
GoTostatement Transferscontroltothelabeledstatement.Thoughitisnot
advisedtouseGoTostatementinyourprogram.
VB.NetStrings
InVB.Net,youcanusestringsasarrayofcharacters,however,morecommonpracticeisto
use the String keyword to declare a string variable. The string keyword is an alias for the
System.Stringclass.
CreatingaStringObject
Youcancreatestringobjectusingoneofthefollowingmethods:
ByassigningastringliteraltoaStringvariable
ByusingaStringclassconstructor
Byusingthestringconcatenationoperator(+)
Byretrievingapropertyorcallingamethodthatreturnsastring
Thefollowingexampledemonstratesthis:
Modulestrings
SubMain()
Dimfname,lname,fullname,greetingsAsString
fname="Rowan"
lname="Atkinson"
fullname=fname+""+lname
Console.WriteLine("FullName:{0}",fullname)
'byusingstringconstructor
DimlettersAsChar()={"H","e","l","l","o"}
greetings=NewString(letters)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 41/158
23/09/2016 VB.NetQuickGuide
Console.WriteLine("Greetings:{0}",greetings)
'methodsreturningString
Dimsarray()AsString={"Hello","From","Tutorials","Point"}
DimmessageAsString=String.Join("",sarray)
Console.WriteLine("Message:{0}",message)
'formattingmethodtoconvertavalue
DimwaitingAsDateTime=NewDateTime(2012,12,12,17,58,1)
DimchatAsString=String.Format("Messagesentat{0:t}on{0:D}",waiting)
Console.WriteLine("Message:{0}",chat)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
FullName:RowanAtkinson
Greetings:Hello
Message:HelloFromTutorialsPoint
Message:Messagesentat5:58PMonWednesday,December12,2012
PropertiesoftheStringClass
TheStringclasshasthefollowingtwoproperties:
S.N PropertyName&Description
1 Chars
GetstheCharobjectataspecifiedpositioninthecurrentStringobject.
2 Length
GetsthenumberofcharactersinthecurrentStringobject.
MethodsoftheStringClass
TheStringclasshasnumerousmethodsthathelpyouinworkingwiththestringobjects.The
followingtableprovidessomeofthemostcommonlyusedmethods:
S.N MethodName&Description
Compares two specified string objects and returns an integer that indicates their
relativepositioninthesortorder.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 42/158
23/09/2016 VB.NetQuickGuide
Compares two specified string objects and returns an integer that indicates their
relativepositioninthesortorder.However,itignorescaseiftheBooleanparameter
istrue.
3 PublicSharedFunctionConcat(str0AsString,str1AsString)AsString
Concatenatestwostringobjects.
Concatenatesthreestringobjects.
Concatenatesfourstringobjects.
6 PublicFunctionContains(valueAsString)AsBoolean
Returns a value indicating whether the specified string object occurs within this
string.
7 PublicSharedFunctionCopy(strAsString)AsString
CreatesanewStringobjectwiththesamevalueasthespecifiedstring.
Copiesaspecifiednumberofcharactersfromaspecifiedpositionofthestringobject
toaspecifiedpositioninanarrayofUnicodecharacters.
9 PublicFunctionEndsWith(valueAsString)AsBoolean
Determineswhethertheendofthestringobjectmatchesthespecifiedstring.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 43/158
23/09/2016 VB.NetQuickGuide
10 PublicFunctionEquals(valueAsString)AsBoolean
Determines whether the current string object and the specified string object have
thesamevalue.
11 PublicSharedFunctionEquals(aAsString,bAsString)AsBoolean
Determineswhethertwospecifiedstringobjectshavethesamevalue.
Replaces one or more format items in a specified string with the string
representationofaspecifiedobject.
13 PublicFunctionIndexOf(valueAsChar)AsInteger
Returns the zerobased index of the first occurrence of the specified Unicode
characterinthecurrentstring.
14 PublicFunctionIndexOf(valueAsString)AsInteger
Returns the zerobased index of the first occurrence of the specified string in this
instance.
Returns the zerobased index of the first occurrence of the specified Unicode
characterinthisstring,startingsearchatthespecifiedcharacterposition.
Returns the zerobased index of the first occurrence of the specified string in this
instance,startingsearchatthespecifiedcharacterposition.
17 PublicFunctionIndexOfAny(anyOfAsChar())AsInteger
Returnsthezerobasedindexofthefirstoccurrenceinthisinstanceofanycharacter
inaspecifiedarrayofUnicodecharacters.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 44/158
23/09/2016 VB.NetQuickGuide
18 PublicFunctionIndexOfAny(anyOfAsChar(),startIndexAsInteger)As
Integer
Returnsthezerobasedindexofthefirstoccurrenceinthisinstanceofanycharacter
inaspecifiedarrayofUnicodecharacters,startingsearchatthespecifiedcharacter
position.
19 PublicFunctionInsert(startIndexAsInteger,valueAsString)AsString
20 PublicSharedFunctionIsNullOrEmpty(valueAsString)AsBoolean
IndicateswhetherthespecifiedstringisnulloranEmptystring.
Concatenates all the elements of a string array, using the specified separator
betweeneachelement.
Concatenatesthespecifiedelementsofastringarray,usingthespecifiedseparator
betweeneachelement.
23 PublicFunctionLastIndexOf(valueAsChar)AsInteger
ReturnsthezerobasedindexpositionofthelastoccurrenceofthespecifiedUnicode
characterwithinthecurrentstringobject.
24 PublicFunctionLastIndexOf(valueAsString)AsInteger
Returns the zerobased index position of the last occurrence of a specified string
withinthecurrentstringobject.
25 PublicFunctionRemove(startIndexAsInteger)AsString
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 45/158
23/09/2016 VB.NetQuickGuide
Removesallthecharactersinthecurrentinstance,beginningataspecifiedposition
andcontinuingthroughthelastposition,andreturnsthestring.
27 PublicFunctionReplace(oldCharAsChar,newCharAsChar)AsString
ReplacesalloccurrencesofaspecifiedUnicodecharacterinthecurrentstringobject
withthespecifiedUnicodecharacterandreturnsthenewstring.
Replaces all occurrences of a specified string in the current string object with the
specifiedstringandreturnsthenewstring.
29 PublicFunctionSplit(ParamArrayseparatorAsChar())AsString()
Returns a string array that contains the substrings in the current string object,
delimitedbyelementsofaspecifiedUnicodecharacterarray.
30 PublicFunctionSplit(separatorAsChar(),countAsInteger)AsString()
Returns a string array that contains the substrings in the current string object,
delimited by elements of a specified Unicode character array. The int parameter
specifiesthemaximumnumberofsubstringstoreturn.
31 PublicFunctionStartsWith(valueAsString)AsBoolean
Determines whether the beginning of this string instance matches the specified
string.
32 PublicFunctionToCharArrayAsChar()
ReturnsaUnicodecharacterarraywithallthecharactersinthecurrentstringobject.
33
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 46/158
23/09/2016 VB.NetQuickGuide
ReturnsaUnicodecharacterarraywithallthecharactersinthecurrentstringobject,
startingfromthespecifiedindexanduptothespecifiedlength.
34 PublicFunctionToLowerAsString
Returnsacopyofthisstringconvertedtolowercase.
35 PublicFunctionToUpperAsString
Returnsacopyofthisstringconvertedtouppercase.
36 PublicFunctionTrimAsString
Removes all leading and trailing whitespace characters from the current String
object.
Theabovelistofmethodsisnotexhaustive,pleasevisitMSDNlibraryforthecompletelist
ofmethodsandStringclassconstructors.
Examples:
Thefollowingexampledemonstratessomeofthemethodsmentionedabove:
ComparingStrings:
#include<include.h>
Modulestrings
SubMain()
Dimstr1,str2AsString
str1="Thisistest"
str2="Thisistext"
If(String.Compare(str1,str2)=0)Then
Console.WriteLine(str1+"and"+str2+
"areequal.")
Else
Console.WriteLine(str1+"and"+str2+
"arenotequal.")
EndIf
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 47/158
23/09/2016 VB.NetQuickGuide
ThisistestandThisistextarenotequal.
StringContainsString:
Modulestrings
SubMain()
Dimstr1AsString
str1="Thisistest"
If(str1.Contains("test"))Then
Console.WriteLine("Thesequence'test'wasfound.")
EndIf
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Thesequence'test'wasfound.
GettingaSubstring:
Modulestrings
SubMain()
DimstrAsString
str="LastnightIdreamtofSanPedro"
Console.WriteLine(str)
DimsubstrAsString=str.Substring(23)
Console.WriteLine(substr)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
LastnightIdreamtofSanPedro
SanPedro.
JoiningStrings:
Modulestrings
SubMain()
DimstrarrayAsString()={"Downthewaywherethenightsaregay",
"Andthesunshinesdailyonthemountaintop",
"Itookatriponasailingship",
"AndwhenIreachedJamaica",
"Imadeastop"}
DimstrAsString=String.Join(vbCrLf,strarray)
Console.WriteLine(str)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Downthewaywherethenightsaregay
Andthesunshinesdailyonthemountaintop
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 48/158
23/09/2016 VB.NetQuickGuide
Itookatriponasailingship
AndwhenIreachedJamaica
Imadeastop
VB.NetDate&Time
Most of the softwares you write need implementing some form of date functions returning
currentdateandtime.Datesaresomuchpartofeverydaylifethatitbecomeseasytowork
with them without thinking. VB.Net also provides powerful tools for date arithmetic that
makesmanipulatingdateseasy.
TheDatedatatypecontainsdatevalues,timevalues,ordateandtimevalues.Thedefault
valueofDateis0:00:00(midnight)onJanuary1,0001.Theequivalent.NETdatatypeis
System.DateTime.
The DateTime structure represents an instant in time, typically expressed as a date and
timeofday
'Declaration
<SerializableAttribute>_
PublicStructureDateTime_
ImplementsIComparable,IFormattable,IConvertible,ISerializable,
IComparable(OfDateTime),IEquatable(OfDateTime)
YoucanalsogetthecurrentdateandtimefromtheDateAndTimeclass.
The DateAndTime module contains the procedures and properties used in date and time
operations.
'Declaration
<StandardModuleAttribute>_
PublicNotInheritableClassDateAndTime
Note:
Both the DateTime structure and the DateAndTime module contain properties like Now
and Today, so often beginners find it confusing. The DateAndTime class belongs to the
Microsoft.VisualBasic namespace and the DateTime structure belongs to the System
namespace.
Therefore, using the later would help you in porting your code to another .Net language
like C#. However, the DateAndTime class/module contains all the legacy date functions
availableinVisualBasic.
PropertiesandMethodsoftheDateTimeStructure
ThefollowingtablelistssomeofthecommonlyusedpropertiesoftheDateTimeStructure:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 49/158
23/09/2016 VB.NetQuickGuide
1 Date Getsthedatecomponentofthisinstance.
2 Day Getsthedayofthemonthrepresentedbythisinstance.
3 DayOfWeek Getsthedayoftheweekrepresentedbythisinstance.
4 DayOfYear Getsthedayoftheyearrepresentedbythisinstance.
5 Hour Getsthehourcomponentofthedaterepresentedbythis
instance.
6 Kind Getsavaluethatindicateswhetherthetimerepresentedbythis
instanceisbasedonlocaltime,CoordinatedUniversalTime
(UTC),orneither.
7 Millisecond Getsthemillisecondscomponentofthedaterepresentedbythis
instance.
8 Minute Getstheminutecomponentofthedaterepresentedbythis
instance.
9 Month Getsthemonthcomponentofthedaterepresentedbythis
instance.
10 Now GetsaDateTimeobjectthatissettothecurrentdateandtime
onthiscomputer,expressedasthelocaltime.
11 Second Getsthesecondscomponentofthedaterepresentedbythis
instance.
12 Ticks Getsthenumberofticksthatrepresentthedateandtimeofthis
instance.
13 TimeOfDay Getsthetimeofdayforthisinstance.
14 Today Getsthecurrentdate.
15 UtcNow GetsaDateTimeobjectthatissettothecurrentdateandtime
onthiscomputer,expressedastheCoordinatedUniversalTime
(UTC).
16 Year Getstheyearcomponentofthedaterepresentedbythis
instance.
ThefollowingtablelistssomeofthecommonlyusedmethodsoftheDateTimestructure:
S.N MethodName&Description
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 50/158
23/09/2016 VB.NetQuickGuide
1 PublicFunctionAdd(valueAsTimeSpan)AsDateTime
ReturnsanewDateTimethataddsthevalueofthespecifiedTimeSpantothevalue
ofthisinstance.
2 PublicFunctionAddDays(valueAsDouble)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofdaystothevalueofthis
instance.
3 PublicFunctionAddHours(valueAsDouble)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofhourstothevalueofthis
instance.
4 PublicFunctionAddMinutes(valueAsDouble)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofminutestothevalueof
thisinstance.
5 PublicFunctionAddMonths(monthsAsInteger)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofmonthstothevalueof
thisinstance.
6 PublicFunctionAddSeconds(valueAsDouble)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofsecondstothevalueof
thisinstance.
7 PublicFunctionAddYears(valueAsInteger)AsDateTime
ReturnsanewDateTimethataddsthespecifiednumberofyearstothevalueofthis
instance.
ComparestwoinstancesofDateTimeandreturnsanintegerthatindicateswhether
thefirstinstanceisearlierthan,thesameas,orlaterthanthesecondinstance.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 51/158
23/09/2016 VB.NetQuickGuide
9 PublicFunctionCompareTo(valueAsDateTime)AsInteger
Compares the value of this instance to a specified DateTime value and returns an
integerthatindicateswhetherthisinstanceisearlierthan,thesameas,orlaterthan
thespecifiedDateTimevalue.
10 PublicFunctionEquals(valueAsDateTime)AsBoolean
Returnsavalueindicatingwhetherthevalueofthisinstanceisequaltothevalueof
thespecifiedDateTimeinstance.
ReturnsavalueindicatingwhethertwoDateTimeinstanceshavethesamedateand
timevalue.
12 PublicOverridesFunctionToStringAsString
Converts the value of the current DateTime object to its equivalent string
representation.
Theabovelistofmethodsisnotexhaustive,pleasevisitMicrosoftdocumentation forthe
completelistofmethodsandpropertiesoftheDateTimestructure.
CreatingaDateTimeObject
YoucancreateaDateTimeobjectinoneofthefollowingways:
ByassigningtheDateTimeobjectadateandtimevaluereturnedbyapropertyor
method.
Byparsingthestringrepresentationofadateandtimevalue.
BycallingtheDateTimestructure'simplicitdefaultconstructor.
Thefollowingexampledemonstratesthis:
ModuleModule1
SubMain()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 52/158
23/09/2016 VB.NetQuickGuide
'DateTimeconstructor:parametersyear,month,day,hour,min,sec
Dimdate1AsNewDate(2012,12,16,12,0,0)
'initializesanewDateTimevalue
Dimdate2AsDate=#12/16/201212:00:52AM#
'usingproperties
Dimdate3AsDate=Date.Now
Dimdate4AsDate=Date.UtcNow
Dimdate5AsDate=Date.Today
Console.WriteLine(date1)
Console.WriteLine(date2)
Console.WriteLine(date3)
Console.WriteLine(date4)
Console.WriteLine(date5)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodewascompiledandexecuted,itproducesthefollowingresult:
12/16/201212:00:00PM
12/16/201212:00:52PM
12/12/201210:22:50PM
12/12/201212:00:00PM
GettingtheCurrentDateandTime:
ThefollowingprogramsdemonstratehowtogetthecurrentdateandtimeinVB.Net:
CurrentTime:
ModuledateNtime
SubMain()
Console.Write("CurrentTime:")
Console.WriteLine(Now.ToLongTimeString)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
CurrentTime:11:05:32AM
CurrentDate:
ModuledateNtime
SubMain()
Console.WriteLine("CurrentDate:")
DimdtAsDate=Today
Console.WriteLine("Todayis:{0}",dt)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 53/158
23/09/2016 VB.NetQuickGuide
Todayis:12/11/201212:00:00AM
FormattingDate
A Date literal should be enclosed within hash signs (# #), and specified in the format
M/d/yyyy,forexample#12/16/2012#.Otherwise,yourcodemaychangedependingonthe
localeinwhichyourapplicationisrunning.
Forexample,youspecifiedDateliteralof#2/6/2012#forthedateFebruary6,2012.Itis
alright for the locale that uses mm/dd/yyyy format. However, in a locale that uses
dd/mm/yyyy format, your literal would compile to June 2, 2012. If a locale uses another
formatsay,yyyy/mm/dd,theliteralwouldbeinvalidandcauseacompilererror.
ToconvertaDateliteraltotheformatofyourlocaleortoacustomformat,usetheFormat
functionofStringclass,specifyingeitherapredefinedoruserdefineddateformat.
Thefollowingexampledemonstratesthis.
ModuledateNtime
SubMain()
Console.WriteLine("IndiaWinsFreedom:")
DimindependenceDayAsNewDate(1947,8,15,0,0,0)
'Useformatspecifierstocontrolthedatedisplay.
Console.WriteLine("Format'd:'"&independenceDay.ToString("d"))
Console.WriteLine("Format'D:'"&independenceDay.ToString("D"))
Console.WriteLine("Format't:'"&independenceDay.ToString("t"))
Console.WriteLine("Format'T:'"&independenceDay.ToString("T"))
Console.WriteLine("Format'f:'"&independenceDay.ToString("f"))
Console.WriteLine("Format'F:'"&independenceDay.ToString("F"))
Console.WriteLine("Format'g:'"&independenceDay.ToString("g"))
Console.WriteLine("Format'G:'"&independenceDay.ToString("G"))
Console.WriteLine("Format'M:'"&independenceDay.ToString("M"))
Console.WriteLine("Format'R:'"&independenceDay.ToString("R"))
Console.WriteLine("Format'y:'"&independenceDay.ToString("y"))
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
IndiaWinsFreedom:
Format'd:'8/15/1947
Format'D:'Friday,August15,1947
Format't:'12:00AM
Format'T:'12:00:00AM
Format'f:'Friday,August15,194712:00AM
Format'F:'Friday,August15,194712:00:00AM
Format'g:'8/15/194712:00AM
Format'G:'8/15/194712:00:00AM
Format'M:'8/15/1947August15
Format'R:'Fri,15August194700:00:00GMT
Format'y:'August,1947
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 54/158
23/09/2016 VB.NetQuickGuide
PredefinedDate/TimeFormats
The following table identifies the predefined date and time format names. These may be
usedbynameasthestyleargumentfortheFormatfunction:
Format Description
GeneralDate,orG Displaysadateand/ortime.Forexample,1/12/201207:07:30AM.
LongDate,Medium Displaysadateaccordingtoyourcurrentculture'slongdateformat.
Date,orD Forexample,Sunday,December16,2012.
ShortDate,ord Displaysadateusingyourcurrentculture'sshortdateformat.For
example,12/12/2012.
LongTime,Medium Displaysatimeusingyourcurrentculture'slongtimeformattypically
Time,orT includeshours,minutes,seconds.Forexample,01:07:30AM.
ShortTimeort Displaysatimeusingyourcurrentculture'sshorttimeformat.For
example,11:07AM.
f Displaysthelongdateandshorttimeaccordingtoyourcurrent
culture'sformat.Forexample,Sunday,December16,201212:15AM.
F Displaysthelongdateandlongtimeaccordingtoyourcurrentculture's
format.Forexample,Sunday,December16,201212:15:31AM.
g Displaystheshortdateandshorttimeaccordingtoyourcurrent
culture'sformat.Forexample,12/16/201212:15AM.
M,m Displaysthemonthandthedayofadate.Forexample,December16.
R,r FormatsthedateaccordingtotheRFC1123Patternproperty.
s Formatsthedateandtimeasasortableindex.Forexample,201212
16T12:07:31.
u FormatsthedateandtimeasaGMTsortableindex.Forexample,
2012121612:15:31Z.
U FormatsthedateandtimewiththelongdateandlongtimeasGMT.
Forexample,Sunday,December16,20126:07:31PM.
Y,y Formatsthedateastheyearandmonth.Forexample,December,
2012.
Forotherformatslikeuserdefinedformats,pleaseconsultMicrosoftDocumentation .
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 55/158
23/09/2016 VB.NetQuickGuide
PropertiesandMethodsoftheDateAndTimeClass
The following table lists some of the commonly used properties of the DateAndTime
Class:
1 Date ReturnsorsetsaStringvaluerepresentingthecurrentdate
accordingtoyoursystem.
2 Now ReturnsaDatevaluecontainingthecurrentdateandtime
accordingtoyoursystem.
3 TimeOfDay ReturnsorsetsaDatevaluecontainingthecurrenttimeofday
accordingtoyoursystem.
4 Timer ReturnsaDoublevaluerepresentingthenumberofseconds
elapsedsincemidnight.
5 TimeString ReturnsorsetsaStringvaluerepresentingthecurrenttimeof
dayaccordingtoyoursystem.
6 Today Getsthecurrentdate.
ThefollowingtablelistssomeofthecommonlyusedmethodsoftheDateAndTimeclass:
S.N MethodName&Description
Returns a Date value containing a date and time value to which a specified time
intervalhasbeenadded.
Returns a Date value containing a date and time value to which a specified time
intervalhasbeenadded.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 56/158
23/09/2016 VB.NetQuickGuide
Returns a Long value specifying the number of time intervals between two Date
values.
ReturnsanIntegervaluecontainingthespecifiedcomponentofagivenDatevalue.
5 PublicSharedFunctionDay(DateValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom1through31representingthedayofthemonth.
6 PublicSharedFunctionHour(TimeValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom0through23representingthehouroftheday.
7 PublicSharedFunctionMinute(TimeValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom0through59representingtheminuteofthehour.
8 PublicSharedFunctionMonth(DateValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom1through12representingthemonthoftheyear.
ReturnsaStringvaluecontainingthenameofthespecifiedmonth.
10 PublicSharedFunctionSecond(TimeValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom0through59representingthesecondoftheminute.
11 PublicOverridableFunctionToStringAsString
Returnsastringthatrepresentsthecurrentobject.
12 PublicSharedFunctionWeekday(DateValueAsDateTime,DayOfWeekAs
FirstDayOfWeek)AsInteger
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 57/158
23/09/2016 VB.NetQuickGuide
ReturnsanIntegervaluecontaininganumberrepresentingthedayoftheweek.
ReturnsaStringvaluecontainingthenameofthespecifiedweekday.
14 PublicSharedFunctionYear(DateValueAsDateTime)AsInteger
ReturnsanIntegervaluefrom1through9999representingtheyear.
The above list is not exhaustive. For complete list of properties and methods of the
DateAndTimeclass,pleaseconsultMicrosoftDocumentation .
Thefollowingprogramdemonstratessomeoftheseandmethods:
ModuleModule1
SubMain()
DimbirthdayAsDate
DimbdayAsInteger
DimmonthAsInteger
DimmonthnameAsString
'Assignadateusingstandardshortformat.
birthday=#7/27/1998#
bday=Microsoft.VisualBasic.DateAndTime.Day(birthday)
month=Microsoft.VisualBasic.DateAndTime.Month(birthday)
monthname=Microsoft.VisualBasic.DateAndTime.MonthName(month)
Console.WriteLine(birthday)
Console.WriteLine(bday)
Console.WriteLine(month)
Console.WriteLine(monthname)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
7/27/199812:00:00AM
27
7
July
VB.NetArrays
Anarraystoresafixedsizesequentialcollectionofelementsofthesametype.Anarrayis
used to store a collection of data, but it is often more useful to think of an array as a
collectionofvariablesofthesametype.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 58/158
23/09/2016 VB.NetQuickGuide
All arrays consist of contiguous memory locations. The lowest address corresponds to the
firstelementandthehighestaddresstothelastelement.
CreatingArraysinVB.Net
TodeclareanarrayinVB.Net,youusetheDimstatement.Forexample,
DimintData(30)'anarrayof31elements
DimstrData(20)AsString 'anarrayof21strings
DimtwoDarray(10,20)AsInteger 'atwodimensionalarrayofintegers
Dimranges(10,100) 'atwodimensionalarray
Youcanalsoinitializethearrayelementswhiledeclaringthearray.Forexample,
DimintData()AsInteger={12,16,20,24,28,32}
Dimnames()AsString={"Karthik","Sandhya",_
"Shivangi","Ashwitha","Somnath"}
DimmiscData()AsObject={"HelloWorld",12d,16ui,"A"c}
Theelementsinanarraycanbestoredandaccessedbyusingtheindexofthearray.The
followingprogramdemonstratesthis:
ModulearrayApl
SubMain()
Dimn(10)AsInteger'nisanarrayof11integers'
Dimi,jAsInteger
'initializeelementsofarrayn'
Fori=0To10
n(i)=i+100'setelementatlocationitoi+100
Nexti
'outputeacharrayelement'svalue'
Forj=0To10
Console.WriteLine("Element({0})={1}",j,n(j))
Nextj
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Element(0)=100
Element(1)=101
Element(2)=102
Element(3)=103
Element(4)=104
Element(5)=105
Element(6)=106
Element(7)=107
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 59/158
23/09/2016 VB.NetQuickGuide
Element(8)=108
Element(9)=109
Element(10)=110
DynamicArrays
Dynamicarraysarearraysthatcanbedimensionedandredimensionedaspartheneedof
theprogram.YoucandeclareadynamicarrayusingtheReDimstatement.
SyntaxforReDimstatement:
ReDim[Preserve]arrayname(subscripts)
Where,
The Preserve keyword helps to preserve the data in an existing array, when you
resizeit.
arraynameisthenameofthearraytoredimension.
subscriptsspecifiesthenewdimension.
ModulearrayApl
SubMain()
Dimmarks()AsInteger
ReDimmarks(2)
marks(0)=85
marks(1)=75
marks(2)=90
ReDimPreservemarks(10)
marks(3)=80
marks(4)=76
marks(5)=92
marks(6)=99
marks(7)=79
marks(8)=75
Fori=0To10
Console.WriteLine(i&vbTab&marks(i))
Nexti
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 60/158
23/09/2016 VB.NetQuickGuide
9 0
10 0
MultiDimensionalArrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular
arrays.
Youcandeclarea2dimensionalarrayofstringsas:
DimtwoDStringArray(10,20)AsString
or,a3dimensionalarrayofIntegervariables:
DimthreeDIntArray(10,10,10)AsInteger
Thefollowingprogramdemonstratescreatingandusinga2dimensionalarray:
ModulearrayApl
SubMain()
'anarraywith5rowsand2columns
Dima(,)AsInteger={{0,0},{1,2},{2,4},{3,6},{4,8}}
Dimi,jAsInteger
'outputeacharrayelement'svalue'
Fori=0To4
Forj=0To1
Console.WriteLine("a[{0},{1}]={2}",i,j,a(i,j))
Nextj
Nexti
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
a[0,0]:0
a[0,1]:0
a[1,0]:1
a[1,1]:2
a[2,0]:2
a[2,1]:4
a[3,0]:3
a[3,1]:6
a[4,0]:4
a[4,1]:8
JaggedArray
A Jagged array is an array of arrays. The follwoing code shows declaring a jagged array
namedscoresofIntegers:
DimscoresAsInteger()()=NewInteger(5)(){}
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 61/158
23/09/2016 VB.NetQuickGuide
Thefollowingexampleillustratesusingajaggedarray:
ModulearrayApl
SubMain()
'ajaggedarrayof5arrayofintegers
DimaAsInteger()()=NewInteger(4)(){}
a(0)=NewInteger(){0,0}
a(1)=NewInteger(){1,2}
a(2)=NewInteger(){2,4}
a(3)=NewInteger(){3,6}
a(4)=NewInteger(){4,8}
Dimi,jAsInteger
'outputeacharrayelement'svalue
Fori=0To4
Forj=0To1
Console.WriteLine("a[{0},{1}]={2}",i,j,a(i)(j))
Nextj
Nexti
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
a[0][0]:0
a[0][1]:0
a[1][0]:1
a[1][1]:2
a[2][0]:2
a[2][1]:4
a[3][0]:3
a[3][1]:6
a[4][0]:4
a[4][1]:8
TheArrayClass
The Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace.TheArrayclassprovidesvariouspropertiesandmethodstoworkwitharrays.
PropertiesoftheArrayClass
The following table provides some of the most commonly used properties of the Array
class:
S.N PropertyName&Description
1 IsFixedSize
GetsavalueindicatingwhethertheArrayhasafixedsize.
2 IsReadOnly
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 62/158
23/09/2016 VB.NetQuickGuide
GetsavalueindicatingwhethertheArrayisreadonly.
3 Length
Gets a 32bit integer that represents the total number of elements in all the
dimensionsoftheArray.
4 LongLength
Gets a 64bit integer that represents the total number of elements in all the
dimensionsoftheArray.
5 Rank
Getstherank(numberofdimensions)oftheArray.
MethodsoftheArrayClass
ThefollowingtableprovidessomeofthemostcommonlyusedmethodsoftheArrayclass:
S.N MethodName&Description
SetsarangeofelementsintheArraytozero,tofalse,ortonull,dependingonthe
elementtype.
2 PublicSharedSubCopy(sourceArrayAsArray,destinationArrayAsArray,
lengthAsInteger)
Copies a range of elements from an Array starting at the first element and pastes
themintoanotherArraystartingatthefirstelement.Thelengthisspecifiedasa32
bitinteger.
3 PublicSubCopyTo(arrayAsArray,indexAsInteger)
Copies all the elements of the current onedimensional Array to the specified one
dimensional Array starting at the specified destination Array index. The index is
specifiedasa32bitinteger.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 63/158
23/09/2016 VB.NetQuickGuide
4 PublicFunctionGetLength(dimensionAsInteger)AsInteger
Gets a 32bit integer that represents the number of elements in the specified
dimensionoftheArray.
5 PublicFunctionGetLongLength(dimensionAsInteger)AsLong
Gets a 64bit integer that represents the number of elements in the specified
dimensionoftheArray.
6 PublicFunctionGetLowerBound(dimensionAsInteger)AsInteger
GetsthelowerboundofthespecifieddimensionintheArray.
7 PublicFunctionGetTypeAsType
GetstheTypeofthecurrentinstance(InheritedfromObject).
8 PublicFunctionGetUpperBound(dimensionAsInteger)AsInteger
GetstheupperboundofthespecifieddimensionintheArray.
9 PublicFunctionGetValue(indexAsInteger)AsObject
GetsthevalueatthespecifiedpositionintheonedimensionalArray.Theindexis
specifiedasa32bitinteger.
Searchesforthespecifiedobjectandreturnstheindexofthefirstoccurrencewithin
theentireonedimensionalArray.
11 PublicSharedSubReverse(arrayAsArray)
ReversesthesequenceoftheelementsintheentireonedimensionalArray.
12 PublicSubSetValue(valueAsObject,indexAsInteger)
SetsavaluetotheelementatthespecifiedpositionintheonedimensionalArray.
Theindexisspecifiedasa32bitinteger.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 64/158
23/09/2016 VB.NetQuickGuide
13 PublicSharedSubSort(arrayAsArray)
14 PublicOverridableFunctionToStringAsString
Returnsastringthatrepresentsthecurrentobject(InheritedfromObject).
For complete list of Array class properties and methods, please consult Microsoft
documentation.
Example
ThefollowingprogramdemonstratesuseofsomeofthemethodsoftheArrayclass:
ModulearrayApl
SubMain()
DimlistAsInteger()={34,72,13,44,25,30,10}
DimtempAsInteger()=list
DimiAsInteger
Console.Write("OriginalArray:")
ForEachiInlist
Console.Write("{0}",i)
Nexti
Console.WriteLine()
'reversethearray
Array.Reverse(temp)
Console.Write("ReversedArray:")
ForEachiIntemp
Console.Write("{0}",i)
Nexti
Console.WriteLine()
'sortthearray
Array.Sort(list)
Console.Write("SortedArray:")
ForEachiInlist
Console.Write("{0}",i)
Nexti
Console.WriteLine()
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
OriginalArray:34721344253010
ReversedArray:10302544137234
SortedArray:10132530344472
VB.NetCollections
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 65/158
23/09/2016 VB.NetQuickGuide
VB.NetCollections
Collection classes are specialized classes for data storage and retrieval. These classes
providesupportforstacks,queues,lists,andhashtables.Mostcollectionclassesimplement
thesameinterfaces.
VariousCollectionClassesandTheirUsage
ThefollowingarethevariouscommonlyusedclassesoftheSystem.Collectionnamespace.
Clickthefollowinglinkstochecktheirdetails.
Class DescriptionandUseage
Itisbasicallyanalternativetoanarray.However,unlikearray,youcan
addandremoveitemsfromalistataspecifiedpositionusinganindex
and the array resizes itself automatically. It also allows dynamic
memoryallocation,add,searchandsortitemsinthelist.
Hashtable Itusesakeytoaccesstheelementsinthecollection.
Ahashtableisusedwhenyouneedtoaccesselementsbyusingkey,
andyoucanidentifyausefulkeyvalue.Eachiteminthehashtablehas
akey/valuepair.Thekeyisusedtoaccesstheitemsinthecollection.
SortedList Itusesakeyaswellasanindextoaccesstheitemsinalist.
Asortedlistisacombinationofanarrayandahashtable.Itcontainsa
listofitemsthatcanbeaccessedusingakeyoranindex.Ifyouaccess
itemsusinganindex,itisanArrayList,andifyouaccessitemsusinga
key, it is a Hashtable. The collection of items is always sorted by the
keyvalue.
Stack Itrepresentsalastin,firstoutcollectionofobject.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 66/158
23/09/2016 VB.NetQuickGuide
Itisusedwhenyouneedalastin,firstoutaccessofitems.Whenyouadd
aniteminthelist,itiscalledpushingtheitem,andwhenyouremoveit,it
iscalledpoppingtheitem.
Queue Itrepresentsafirstin,firstoutcollectionofobject.
Itisusedwhenyouneedafirstin,firstoutaccessofitems.Whenyou
addaniteminthelist,itiscalledenqueue,andwhenyouremovean
item,itiscalleddeque.
BitArray Itrepresentsanarrayofthebinaryrepresentationusingthevalues
1and0.
Itisusedwhenyouneedtostorethebitsbutdonotknowthenumber
ofbitsinadvance.YoucanaccessitemsfromtheBitArraycollectionby
usinganintegerindex,whichstartsfromzero.
VB.NetFunctions
A procedure is a group of statements that together perform a task when called. After the
procedureisexecuted,thecontrolreturnstothestatementcallingtheprocedure.VB.Nethas
twotypesofprocedures:
Functions
SubproceduresorSubs
Functionsreturnavalue,whereasSubsdonotreturnavalue.
DefiningaFunction
TheFunctionstatementisusedtodeclarethename,parameterandthebodyofafunction.
ThesyntaxfortheFunctionstatementis:
[Modifiers]FunctionFunctionName[(ParameterList)]AsReturnType
[Statements]
EndFunction
Where,
Modifiers: specify the access level of the function possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding overloading,
overriding,sharing,andshadowing.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 67/158
23/09/2016 VB.NetQuickGuide
FunctionName:indicatesthenameofthefunction
ParameterList:specifiesthelistoftheparameters
ReturnType:specifiesthedatatypeofthevariablethefunctionreturns
Example
FollowingcodesnippetshowsafunctionFindMaxthattakestwointegervaluesandreturns
thelargerofthetwo.
FunctionFindMax(ByValnum1AsInteger,ByValnum2AsInteger)AsInteger
'localvariabledeclaration*/
DimresultAsInteger
If(num1>num2)Then
result=num1
Else
result=num2
EndIf
FindMax=result
EndFunction
FunctionReturningaValue
InVB.Net,afunctioncanreturnavaluetothecallingcodeintwoways:
Byusingthereturnstatement
Byassigningthevaluetothefunctionname
ThefollowingexampledemonstratesusingtheFindMaxfunction:
Modulemyfunctions
FunctionFindMax(ByValnum1AsInteger,ByValnum2AsInteger)AsInteger
'localvariabledeclaration*/
DimresultAsInteger
If(num1>num2)Then
result=num1
Else
result=num2
EndIf
FindMax=result
EndFunction
SubMain()
DimaAsInteger=100
DimbAsInteger=200
DimresAsInteger
res=FindMax(a,b)
Console.WriteLine("Maxvalueis:{0}",res)
Console.ReadLine()
EndSub
EndModule
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 68/158
23/09/2016 VB.NetQuickGuide
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Maxvalueis:200
RecursiveFunction
Afunctioncancallitself.Thisisknownasrecursion.Followingisanexamplethatcalculates
factorialforagivennumberusingarecursivefunction:
Modulemyfunctions
Functionfactorial(ByValnumAsInteger)AsInteger
'localvariabledeclaration*/
DimresultAsInteger
If(num=1)Then
Return1
Else
result=factorial(num1)*num
Returnresult
EndIf
EndFunction
SubMain()
'callingthefactorialmethod
Console.WriteLine("Factorialof6is:{0}",factorial(6))
Console.WriteLine("Factorialof7is:{0}",factorial(7))
Console.WriteLine("Factorialof8is:{0}",factorial(8))
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Factorialof6is:720
Factorialof7is:5040
Factorialof8is:40320
ParamArrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into
helpatthesetimes.
Thefollowingexampledemonstratesthis:
Modulemyparamfunc
FunctionAddElements(ParamArrayarrAsInteger())AsInteger
DimsumAsInteger=0
DimiAsInteger=0
ForEachiInarr
sum+=i
Nexti
Returnsum
EndFunction
SubMain()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 69/158
23/09/2016 VB.NetQuickGuide
DimsumAsInteger
sum=AddElements(512,720,250,567,889)
Console.WriteLine("Thesumis:{0}",sum)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Thesumis:2938
PassingArraysasFunctionArguments
You can pass an array as a function argument in VB.Net. The following example
demonstratesthis:
ModulearrayParameter
FunctiongetAverage(ByValarrAsInteger(),ByValsizeAsInteger)AsDouble
'localvariables
DimiAsInteger
DimavgAsDouble
DimsumAsInteger=0
Fori=0Tosize1
sum+=arr(i)
Nexti
avg=sum/size
Returnavg
EndFunction
SubMain()
'anintarraywith5elements'
DimbalanceAsInteger()={1000,2,3,17,50}
DimavgAsDouble
'passpointertothearrayasanargument
avg=getAverage(balance,5)
'outputthereturnedvalue'
Console.WriteLine("Averagevalueis:{0}",avg)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Averagevalueis:214.4
VB.NetSubProcedures
Aswementionedinthepreviouschapter,Subproceduresareproceduresthatdonotreturn
anyvalue.WehavebeenusingtheSubprocedureMaininallourexamples.Wehavebeen
writing console applications so far in these tutorials. When these applications start, the
control goes to the Main Sub procedure, and it in turn, runs any other statements
constitutingthebodyoftheprogram.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 70/158
23/09/2016 VB.NetQuickGuide
DefiningSubProcedures
The Sub statement is used to declare the name, parameter and the body of a sub
procedure.ThesyntaxfortheSubstatementis:
[Modifiers]SubSubName[(ParameterList)]
[Statements]
EndSub
Where,
Modifiers: specify the access level of the procedure possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding overloading,
overriding,sharing,andshadowing.
SubName:indicatesthenameoftheSub
ParameterList:specifiesthelistoftheparameters
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parametershoursandwagesanddisplaysthetotalpayofanemployee:
Modulemysub
SubCalculatePay(ByRefhoursAsDouble,ByRefwageAsDecimal)
'localvariabledeclaration
DimpayAsDouble
pay=hours*wage
Console.WriteLine("TotalPay:{0:C}",pay)
EndSub
SubMain()
'callingtheCalculatePaySubProcedure
CalculatePay(25,10)
CalculatePay(40,20)
CalculatePay(30,27.5)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
TotalPay:$250.00
TotalPay:$800.00
TotalPay:$825.00
PassingParametersbyValue
Thisisthedefaultmechanismforpassingparameterstoamethod.Inthismechanism,when
amethodiscalled,anewstoragelocationiscreatedforeachvalueparameter.Thevaluesof
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 71/158
23/09/2016 VB.NetQuickGuide
theactualparametersarecopiedintothem.So,thechangesmadetotheparameterinside
themethodhavenoeffectontheargument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following
exampledemonstratestheconcept:
ModuleparamByval
Subswap(ByValxAsInteger,ByValyAsInteger)
DimtempAsInteger
temp=x'savethevalueofx
x=y'putyintox
y=temp'puttempintoy
EndSub
SubMain()
'localvariabledefinition
DimaAsInteger=100
DimbAsInteger=200
Console.WriteLine("Beforeswap,valueofa:{0}",a)
Console.WriteLine("Beforeswap,valueofb:{0}",b)
'callingafunctiontoswapthevalues'
swap(a,b)
Console.WriteLine("Afterswap,valueofa:{0}",a)
Console.WriteLine("Afterswap,valueofb:{0}",b)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Beforeswap,valueofa:100
Beforeswap,valueofb:200
Afterswap,valueofa:100
Afterswap,valueofb:200
It shows that there is no change in the values though they had been changed inside the
function.
PassingParametersbyReference
A reference parameter is a reference to a memory location of a variable. When you pass
parametersbyreference,unlikevalueparameters,anewstoragelocationisnotcreatedfor
these parameters. The reference parameters represent the same memory location as the
actualparametersthataresuppliedtothemethod.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following
exampledemonstratesthis:
ModuleparamByref
Subswap(ByRefxAsInteger,ByRefyAsInteger)
DimtempAsInteger
temp=x'savethevalueofx
x=y'putyintox
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 72/158
23/09/2016 VB.NetQuickGuide
y=temp'puttempintoy
EndSub
SubMain()
'localvariabledefinition
DimaAsInteger=100
DimbAsInteger=200
Console.WriteLine("Beforeswap,valueofa:{0}",a)
Console.WriteLine("Beforeswap,valueofb:{0}",b)
'callingafunctiontoswapthevalues'
swap(a,b)
Console.WriteLine("Afterswap,valueofa:{0}",a)
Console.WriteLine("Afterswap,valueofb:{0}",b)
Console.ReadLine()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Beforeswap,valueofa:100
Beforeswap,valueofb:200
Afterswap,valueofa:200
Afterswap,valueofb:100
VB.NetClasses&Objects
Whenyoudefineaclass,youdefineablueprintforadatatype.Thisdoesn'tactuallydefine
anydata,butitdoesdefinewhattheclassnamemeans,thatis,whatanobjectoftheclass
willconsistofandwhatoperationscanbeperformedonsuchanobject.
Objectsareinstancesofaclass.Themethodsandvariablesthatconstituteaclassarecalled
membersoftheclass.
ClassDefinition
AclassdefinitionstartswiththekeywordClassfollowedbytheclassnameandtheclass
body,endedbytheEndClassstatement.Followingisthegeneralformofaclassdefinition:
[<attributelist>][accessmodifier][Shadows][MustInherit|NotInheritable][Partial]_
Classname[(Oftypelist)]
[Inheritsclassname]
[Implementsinterfacenames]
[statements]
EndClass
Where,
attributelistisalistofattributesthatapplytotheclass.Optional.
accessmodifier defines the access levels of the class, it has values as Public,
Protected,Friend,ProtectedFriendandPrivate.Optional.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 73/158
23/09/2016 VB.NetQuickGuide
Shadows indicate that the variable redeclares and hides an identically named
element,orsetofoverloadedelements,inabaseclass.Optional.
MustInheritspecifiesthattheclasscanbeusedonlyasabaseclassandthatyou
cannotcreateanobjectdirectlyfromit,i.e.,anabstractclass.Optional.
NotInheritablespecifiesthattheclasscannotbeusedasabaseclass.
Partialindicatesapartialdefinitionoftheclass.
Inheritsspecifiesthebaseclassitisinheritingfrom.
Implementsspecifiestheinterfacestheclassisinheritingfrom.
ThefollowingexampledemonstratesaBoxclass,withthreedatamembers,length,breadth
andheight:
Modulemybox
ClassBox
PubliclengthAsDouble'Lengthofabox
PublicbreadthAsDouble'Breadthofabox
PublicheightAsDouble'Heightofabox
EndClass
SubMain()
DimBox1AsBox=NewBox()'DeclareBox1oftypeBox
DimBox2AsBox=NewBox()'DeclareBox2oftypeBox
DimvolumeAsDouble=0.0'Storethevolumeofaboxhere
'box1specification
Box1.height=5.0
Box1.length=6.0
Box1.breadth=7.0
'box2specification
Box2.height=10.0
Box2.length=12.0
Box2.breadth=13.0
'volumeofbox1
volume=Box1.height*Box1.length*Box1.breadth
Console.WriteLine("VolumeofBox1:{0}",volume)
'volumeofbox2
volume=Box2.height*Box2.length*Box2.breadth
Console.WriteLine("VolumeofBox2:{0}",volume)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
VolumeofBox1:210
VolumeofBox2:1560
MemberFunctionsandEncapsulation
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 74/158
23/09/2016 VB.NetQuickGuide
Amemberfunctionofaclassisafunctionthathasitsdefinitionoritsprototypewithinthe
classdefinitionlikeanyothervariable.Itoperatesonanyobjectoftheclassofwhichitisa
memberandhasaccesstoallthemembersofaclassforthatobject.
Member variables are attributes of an object (from design perspective) and they are kept
privatetoimplementencapsulation.Thesevariablescanonlybeaccessedusingthepublic
memberfunctions.
Letusputaboveconceptstosetandgetthevalueofdifferentclassmembersinaclass:
Modulemybox
ClassBox
PubliclengthAsDouble'Lengthofabox
PublicbreadthAsDouble'Breadthofabox
PublicheightAsDouble'Heightofabox
PublicSubsetLength(ByVallenAsDouble)
length=len
EndSub
PublicSubsetBreadth(ByValbreAsDouble)
breadth=bre
EndSub
PublicSubsetHeight(ByValheiAsDouble)
height=hei
EndSub
PublicFunctiongetVolume()AsDouble
Returnlength*breadth*height
EndFunction
EndClass
SubMain()
DimBox1AsBox=NewBox()'DeclareBox1oftypeBox
DimBox2AsBox=NewBox()'DeclareBox2oftypeBox
DimvolumeAsDouble=0.0'Storethevolumeofaboxhere
'box1specification
Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)
'box2specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'volumeofbox1
volume=Box1.getVolume()
Console.WriteLine("VolumeofBox1:{0}",volume)
'volumeofbox2
volume=Box2.getVolume()
Console.WriteLine("VolumeofBox2:{0}",volume)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 75/158
23/09/2016 VB.NetQuickGuide
VolumeofBox1:210
VolumeofBox2:1560
ConstructorsandDestructors
A class constructor is a special member Sub of a class that is executed whenever we
createnewobjectsofthatclass.AconstructorhasthenameNewanditdoesnothaveany
returntype.
Followingprogramexplainstheconceptofconstructor:
ClassLine
PrivatelengthAsDouble'Lengthofaline
PublicSubNew()'constructor
Console.WriteLine("Objectisbeingcreated")
EndSub
PublicSubsetLength(ByVallenAsDouble)
length=len
EndSub
PublicFunctiongetLength()AsDouble
Returnlength
EndFunction
SharedSubMain()
DimlineAsLine=NewLine()
'setlinelength
line.setLength(6.0)
Console.WriteLine("Lengthofline:{0}",line.getLength())
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated
Lengthofline:6
Adefaultconstructordoesnothaveanyparameter,butifyouneed,aconstructorcanhave
parameters. Such constructors are called parameterized constructors. This technique
helps you to assign initial value to an object at the time of its creation as shown in the
followingexample:
ClassLine
PrivatelengthAsDouble'Lengthofaline
PublicSubNew(ByVallenAsDouble)'parameterisedconstructor
Console.WriteLine("Objectisbeingcreated,length={0}",len)
length=len
EndSub
PublicSubsetLength(ByVallenAsDouble)
length=len
EndSub
PublicFunctiongetLength()AsDouble
Returnlength
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 76/158
23/09/2016 VB.NetQuickGuide
EndFunction
SharedSubMain()
DimlineAsLine=NewLine(10.0)
Console.WriteLine("Lengthoflinesetbyconstructor:{0}",line.getLength())
'setlinelength
line.setLength(6.0)
Console.WriteLine("LengthoflinesetbysetLength:{0}",line.getLength())
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated,length=10
Lengthoflinesetbyconstructor:10
LengthoflinesetbysetLength:6
AdestructorisaspecialmemberSubofaclassthatisexecutedwheneveranobjectofits
classgoesoutofscope.
AdestructorhasthenameFinalizeanditcanneitherreturnavaluenorcanittakeany
parameters.Destructorcanbeveryusefulforreleasingresourcesbeforecomingoutofthe
programlikeclosingfiles,releasingmemories,etc.
Destructorscannotbeinheritedoroverloaded.
Followingexampleexplainstheconceptofdestructor:
ClassLine
PrivatelengthAsDouble'Lengthofaline
PublicSubNew()'parameterisedconstructor
Console.WriteLine("Objectisbeingcreated")
EndSub
ProtectedOverridesSubFinalize()'destructor
Console.WriteLine("Objectisbeingdeleted")
EndSub
PublicSubsetLength(ByVallenAsDouble)
length=len
EndSub
PublicFunctiongetLength()AsDouble
Returnlength
EndFunction
SharedSubMain()
DimlineAsLine=NewLine()
'setlinelength
line.setLength(6.0)
Console.WriteLine("Lengthofline:{0}",line.getLength())
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Objectisbeingcreated
Lengthofline:6
Objectisbeingdeleted
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 77/158
23/09/2016 VB.NetQuickGuide
SharedMembersofaVB.NetClass
We can define class members as static using the Shared keyword. When we declare a
member of a class as Shared, it means no matter how many objects of the class are
created,thereisonlyonecopyofthemember.
ThekeywordSharedimpliesthatonlyoneinstanceofthememberexistsforaclass.Shared
variablesareusedfordefiningconstantsbecausetheirvaluescanberetrievedbyinvoking
theclasswithoutcreatinganinstanceofit.
Sharedvariablescanbeinitializedoutsidethememberfunctionorclassdefinition.Youcan
alsoinitializeSharedvariablesinsidetheclassdefinition.
YoucanalsodeclareamemberfunctionasShared.SuchfunctionscanaccessonlyShared
variables.TheSharedfunctionsexistevenbeforetheobjectiscreated.
Thefollowingexampledemonstratestheuseofsharedmembers:
ClassStaticVar
PublicSharednumAsInteger
PublicSubcount()
num=num+1
EndSub
PublicSharedFunctiongetNum()AsInteger
Returnnum
EndFunction
SharedSubMain()
DimsAsStaticVar=NewStaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Valueofvariablenum:{0}",StaticVar.getNum())
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofvariablenum:3
Inheritance
Oneofthemostimportantconceptsinobjectorientedprogrammingisthatofinheritance.
Inheritance allows us to define a class in terms of another class which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionalityandfastimplementationtime.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 78/158
23/09/2016 VB.NetQuickGuide
When creating a class, instead of writing completely new data members and member
functions,theprogrammercandesignatethatthenewclassshouldinheritthemembersof
anexistingclass.Thisexistingclassiscalledthebaseclass,andthenewclassisreferredto
asthederivedclass.
Base&DerivedClasses:
Aclasscanbederivedfrommorethanoneclassorinterface,whichmeansthatitcaninherit
dataandfunctionsfrommultiplebaseclassesorinterfaces.
ThesyntaxusedinVB.Netforcreatingderivedclassesisasfollows:
<accessspecifier>Class<base_class>
...
EndClass
Class<derived_class>:Inherits<base_class>
...
EndClass
ConsiderabaseclassShapeanditsderivedclassRectangle:
'Baseclass
ClassShape
ProtectedwidthAsInteger
ProtectedheightAsInteger
PublicSubsetWidth(ByValwAsInteger)
width=w
EndSub
PublicSubsetHeight(ByValhAsInteger)
height=h
EndSub
EndClass
'Derivedclass
ClassRectangle:InheritsShape
PublicFunctiongetArea()AsInteger
Return(width*height)
EndFunction
EndClass
ClassRectangleTester
SharedSubMain()
DimrectAsRectangle=NewRectangle()
rect.setWidth(5)
rect.setHeight(7)
'Printtheareaoftheobject.
Console.WriteLine("Totalarea:{0}",rect.getArea())
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Totalarea:35
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 79/158
23/09/2016 VB.NetQuickGuide
BaseClassInitialization
The derived class inherits the base class member variables and member methods.
Therefore,thesuperclassobjectshouldbecreatedbeforethesubclassiscreated.Thesuper
classorthebaseclassisimplicitlyknownasMyBaseinVB.Net
Thefollowingprogramdemonstratesthis:
'Baseclass
ClassRectangle
ProtectedwidthAsDouble
ProtectedlengthAsDouble
PublicSubNew(ByVallAsDouble,ByValwAsDouble)
length=l
width=w
EndSub
PublicFunctionGetArea()AsDouble
Return(width*length)
EndFunction
PublicOverridableSubDisplay()
Console.WriteLine("Length:{0}",length)
Console.WriteLine("Width:{0}",width)
Console.WriteLine("Area:{0}",GetArea())
EndSub
'endclassRectangle
EndClass
'Derivedclass
ClassTabletop:InheritsRectangle
PrivatecostAsDouble
PublicSubNew(ByVallAsDouble,ByValwAsDouble)
MyBase.New(l,w)
EndSub
PublicFunctionGetCost()AsDouble
DimcostAsDouble
cost=GetArea()*70
Returncost
EndFunction
PublicOverridesSubDisplay()
MyBase.Display()
Console.WriteLine("Cost:{0}",GetCost())
EndSub
'endclassTabletop
EndClass
ClassRectangleTester
SharedSubMain()
DimtAsTabletop=NewTabletop(4.5,7.5)
t.Display()
Console.ReadKey()
EndSub
EndClass
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Length:4.5
Width:7.5
Area:33.75
Cost:2362.5
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 80/158
23/09/2016 VB.NetQuickGuide
VB.Netsupportsmultipleinheritance.
VB.NetExceptionHandling
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Anexceptionisa
responsetoanexceptionalcircumstancethatariseswhileaprogramisrunning,suchasan
attempttodividebyzero.
Exceptionsprovideawaytotransfercontrolfromonepartofaprogramtoanother.VB.Net
exceptionhandlingisbuiltuponfourkeywords:Try,Catch,FinallyandThrow.
Try: A Try block identifies a block of code for which particular exceptions will be
activated.It'sfollowedbyoneormoreCatchblocks.
Catch:Aprogramcatchesanexceptionwithanexceptionhandlerattheplaceina
program where you want to handle the problem. The Catch keyword indicates the
catchingofanexception.
Finally:TheFinallyblockisusedtoexecuteagivensetofstatements,whetheran
exceptionisthrownornotthrown.Forexample,ifyouopenafile,itmustbeclosed
whetheranexceptionisraisedornot.
Throw: A program throws an exception when a problem shows up. This is done
usingaThrowkeyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a
combinationoftheTryandCatchkeywords.ATry/Catchblockisplacedaroundthecodethat
mightgenerateanexception.CodewithinaTry/Catchblockisreferredtoasprotectedcode,
andthesyntaxforusingTry/Catchlookslikethefollowing:
Try
[tryStatements]
[ExitTry]
[Catch[exception[Astype]][Whenexpression]
[catchStatements]
[ExitTry]]
[Catch...]
[Finally
[finallyStatements]]
EndTry
You can list down multiple catch statements to catch different type of exceptions in case
yourtryblockraisesmorethanoneexceptionindifferentsituations.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 81/158
23/09/2016 VB.NetQuickGuide
ExceptionClassesin.NetFramework
Inthe.NetFramework,exceptionsarerepresentedbyclasses.Theexceptionclassesin.Net
Framework are mainly directly or indirectly derived from the System.Exception class.
Some of the exception classes derived from the System.Exception class are the
System.ApplicationExceptionandSystem.SystemExceptionclasses.
TheSystem.SystemExceptionclassisthebaseclassforallpredefinedsystemexception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemExceptionclass:
ExceptionClass Description
System.IO.IOException HandlesI/Oerrors.
System.IndexOutOfRangeException Handleserrorsgeneratedwhenamethodreferstoan
arrayindexoutofrange.
System.ArrayTypeMismatchException Handleserrorsgeneratedwhentypeismismatchedwith
thearraytype.
System.NullReferenceException Handleserrorsgeneratedfromdeferencinganullobject.
System.DivideByZeroException Handleserrorsgeneratedfromdividingadividendwith
zero.
System.InvalidCastException Handleserrorsgeneratedduringtypecasting.
System.OutOfMemoryException Handleserrorsgeneratedfrominsufficientfreememory.
System.StackOverflowException Handleserrorsgeneratedfromstackoverflow.
HandlingExceptions
VB.Netprovidesastructuredsolutiontotheexceptionhandlingproblemsintheformoftry
andcatchblocks.Usingtheseblocksthecoreprogramstatementsareseparatedfromthe
errorhandlingstatements.
ModuleexceptionProg
Subdivision(ByValnum1AsInteger,ByValnum2AsInteger)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 82/158
23/09/2016 VB.NetQuickGuide
DimresultAsInteger
Try
result=num1\num2
CatcheAsDivideByZeroException
Console.WriteLine("Exceptioncaught:{0}",e)
Finally
Console.WriteLine("Result:{0}",result)
EndTry
EndSub
SubMain()
division(25,0)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Exceptioncaught:System.DivideByZeroException:Attemptedtodividebyzero.
at...
Result:0
CreatingUserDefinedExceptions
Youcanalsodefineyourownexception.Userdefinedexceptionclassesarederivedfromthe
ApplicationExceptionclass.Thefollowingexampledemonstratesthis:
ModuleexceptionProg
PublicClassTempIsZeroException:InheritsApplicationException
PublicSubNew(ByValmessageAsString)
MyBase.New(message)
EndSub
EndClass
PublicClassTemperature
DimtemperatureAsInteger=0
SubshowTemp()
If(temperature=0)Then
Throw(NewTempIsZeroException("ZeroTemperaturefound"))
Else
Console.WriteLine("Temperature:{0}",temperature)
EndIf
EndSub
EndClass
SubMain()
DimtempAsTemperature=NewTemperature()
Try
temp.showTemp()
CatcheAsTempIsZeroException
Console.WriteLine("TempIsZeroException:{0}",e.Message)
EndTry
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
TempIsZeroException:ZeroTemperaturefound
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 83/158
23/09/2016 VB.NetQuickGuide
ThrowingObjects
YoucanthrowanobjectifitiseitherdirectlyorindirectlyderivedfromtheSystem.Exception
class.
Youcanuseathrowstatementinthecatchblocktothrowthepresentobjectas:
Throw[expression]
Thefollowingprogramdemonstratesthis:
ModuleexceptionProg
SubMain()
Try
ThrowNewApplicationException("Acustomexception_
isbeingthrownhere...")
CatcheAsException
Console.WriteLine(e.Message)
Finally
Console.WriteLine("NowinsidetheFinallyBlock")
EndTry
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Acustomexceptionisbeingthrownhere...
NowinsidetheFinallyBlock
VB.NetFileHandling
Afileisacollectionofdatastoredinadiskwithaspecificnameandadirectorypath.When
afileisopenedforreadingorwriting,itbecomesastream.
The stream is basically the sequence of bytes passing through the communication path.
There are two main streams: the input stream and the output stream. The input
streamisusedforreadingdatafromfile(readoperation)andtheoutputstreamisused
forwritingintothefile(writeoperation).
VB.NetI/OClasses
The System.IO namespace has various classes that are used for performing various
operationswithfiles,likecreatinganddeletingfiles,readingfromorwritingtoafile,closing
afile,etc.
The following table shows some commonly used nonabstract classes in the System.IO
namespace:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 84/158
23/09/2016 VB.NetQuickGuide
I/OClass Description
BinaryReader Readsprimitivedatafromabinarystream.
BinaryWriter Writesprimitivedatainbinaryformat.
BufferedStream Atemporarystorageforastreamofbytes.
Directory Helpsinmanipulatingadirectorystructure.
DirectoryInfo Usedforperformingoperationsondirectories.
DriveInfo Providesinformationforthedrives.
File Helpsinmanipulatingfiles.
FileInfo Usedforperformingoperationsonfiles.
FileStream Usedtoreadfromandwritetoanylocationinafile.
MemoryStream Usedforrandomaccessofstreameddatastoredinmemory.
Path Performsoperationsonpathinformation.
StreamReader Usedforreadingcharactersfromabytestream.
StreamWriter Isusedforwritingcharacterstoastream.
StringReader Isusedforreadingfromastringbuffer.
StringWriter Isusedforwritingintoastringbuffer.
TheFileStreamClass
The FileStream class in the System.IO namespace helps in reading from, writing to and
closingfiles.ThisclassderivesfromtheabstractclassStream.
You need to create a FileStream object to create a new file or open an existing file. The
syntaxforcreatingaFileStreamobjectisasfollows:
Dim<object_name>AsFileStream=NewFileStream(<file_name>,<FileModeEnumerator>,<FileAccessEnumerato
Forexample,forcreatingaFileStreamobjectFforreadingafilenamedsample.txt:
Dimf1AsFileStream=NewFileStream("sample.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite)
Parameter Description
FileMode
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 85/158
23/09/2016 VB.NetQuickGuide
Append:Itopensanexistingfileandputscursorattheendof
file,orcreatesthefile,ifthefiledoesnotexist.
Create:Itcreatesanewfile.
CreateNew:Itspecifiestotheoperatingsystemthatitshould
createanewfile.
Open:Itopensanexistingfile.
FileShare FileShareenumeratorshavethefollowingmembers:
None:Itdeclinessharingofthecurrentfile
Read:Itallowsopeningthefileforreading
ReadWrite:Itallowsopeningthefileforreadingandwriting
Write:Itallowsopeningthefileforwriting
Example:
ThefollowingprogramdemonstratesuseoftheFileStreamclass:
ImportsSystem.IO
ModulefileProg
SubMain()
Dimf1AsFileStream=NewFileStream("sample.txt",_
FileMode.OpenOrCreate,FileAccess.ReadWrite)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 86/158
23/09/2016 VB.NetQuickGuide
DimiAsInteger
Fori=0To20
f1.WriteByte(CByte(i))
Nexti
f1.Position=0
Fori=0To20
Console.Write("{0}",f1.ReadByte())
Nexti
f1.Close()
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
12345678910111213141516171819201
AdvancedFileOperationsinVB.Net
The preceding example provides simple file operations in VB.Net. However, to utilize the
immense powers of System.IO classes, you need to know the commonly used properties
andmethodsoftheseclasses.
We will discuss these classes and the operations they perform in the following sections.
Pleaseclickthelinksprovidedtogettotheindividualsections:
TopicandDescription
ReadingfromandWritingintoTextfiles
It involves reading from and writing into text files. The StreamReader and
StreamWriterclasseshelptoaccomplishit.
ReadingfromandWritingintoBinaryfiles
It involves reading from and writing into binary files. The BinaryReader and
BinaryWriterclasseshelptoaccomplishthis.
ManipulatingtheWindowsfilesystem
It gives a VB.Net programmer the ability to browse and locate Windows files and
directories.
VB.NetBasicControls
AnobjectisatypeofuserinterfaceelementyoucreateonaVisualBasicformbyusinga
toolboxcontrol.Infact,inVisualBasic,theformitselfisanobject.EveryVisualBasiccontrol
consistsofthreeimportantelements:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 87/158
23/09/2016 VB.NetQuickGuide
Propertieswhichdescribetheobject,
Methodscauseanobjecttodosomethingand
Eventsarewhathappenswhenanobjectdoessomething.
ControlProperties
AlltheVisualBasicObjectscanbemoved,resizedorcustomizedbysettingtheirproperties.
ApropertyisavalueorcharacteristicheldbyaVisualBasicobject,suchasCaptionorFore
Color.
PropertiescanbesetatdesigntimebyusingthePropertieswindoworatruntimebyusing
statementsintheprogramcode.
Object.Property=Value
Where
Objectisthenameoftheobjectyou'recustomizing.
Propertyisthecharacteristicyouwanttochange.
Valueisthenewpropertysetting.
Forexample,
Form1.Caption="Hello"
YoucansetanyoftheformpropertiesusingPropertiesWindow.Mostofthepropertiescan
besetorreadduringapplicationexecution.YoucanrefertoMicrosoftdocumentationfora
completelistofpropertiesassociatedwithdifferentcontrolsandrestrictionsappliedtothem.
ControlMethods
A method is a procedure created as a member of a class and they cause an object to do
something.Methodsareusedtoaccessormanipulatethecharacteristicsofanobjectora
variable.Therearemainlytwocategoriesofmethodsyouwilluseinyourclasses:
IfyouareusingacontrolsuchasoneofthoseprovidedbytheToolbox,youcancall
anyofitspublicmethods.Therequirementsofsuchamethoddependontheclass
beingused.
If none of the existing methods can perform your desired task, you can add a
methodtoaclass.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 88/158
23/09/2016 VB.NetQuickGuide
Forexample,theMessageBoxcontrolhasamethodnamedShow,whichiscalledinthecode
snippetbelow:
PublicClassForm1
PrivateSubButton1_Click(ByValsenderAsSystem.Object,ByValeAsSystem.EventArgs)
HandlesButton1.Click
MessageBox.Show("Hello,World")
EndSub
EndClass
ControlEvents
Aneventisasignalthatinformsanapplicationthatsomethingimportanthasoccurred.For
example,whenauserclicksacontrolonaform,theformcanraiseaClickeventandcalla
procedurethathandlestheevent.TherearevarioustypesofeventsassociatedwithaForm
likeclick,doubleclick,close,load,resize,etc.
FollowingisthedefaultstructureofaformLoadeventhandlersubroutine.Youcanseethis
code by double clicking the code which will give you a complete list of the all events
associatedwithFormcontrol:
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'eventhandlercodegoeshere
EndSub
BasicControls
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalitiesofallthesecontrolsaredefinedintherespectivecontrolclasses.Thecontrol
classesaredefinedintheSystem.Windows.Formsnamespace.
Thefollowingtablelistssomeofthecommonlyusedcontrols:
S.N. Widget&Description
1 Forms
Thecontainerforallthecontrolsthatmakeuptheuserinterface.
2 TextBox
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 89/158
23/09/2016 VB.NetQuickGuide
ItrepresentsaWindowstextboxcontrol.
3 Label
ItrepresentsastandardWindowslabel.
4 Button
ItrepresentsaWindowsbuttoncontrol.
5 ListBox
ItrepresentsaWindowscontroltodisplayalistofitems.
6 ComboBox
ItrepresentsaWindowscomboboxcontrol.
7 RadioButton
It enables the user to select a single option from a group of choices when paired
withotherRadioButtoncontrols.
8 CheckBox
ItrepresentsaWindowsCheckBox.
9 PictureBox
ItrepresentsaWindowspictureboxcontrolfordisplayinganimage.
10 ProgressBar
ItrepresentsaWindowsprogressbarcontrol.
11 ScrollBar
ItImplementsthebasicfunctionalityofascrollbarcontrol.
12 DateTimePicker
ItrepresentsaWindowscontrolthatallowstheusertoselectadateandatimeand
todisplaythedateandtimewithaspecifiedformat.
13 TreeView
It displays a hierarchical collection of labeled items, each represented by a
TreeNode.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 90/158
23/09/2016 VB.NetQuickGuide
14 ListView
ItrepresentsaWindowslistviewcontrol,whichdisplaysacollectionofitemsthat
canbedisplayedusingoneoffourdifferentviews.
VB.NetDialogBoxes
There are many builtin dialog boxes to be used in Windows forms for various tasks like
openingandsavingfiles,printingapage,providingchoicesforcolors,fonts,pagesetup,etc.,
to the user of an application. These builtin dialog boxes reduce the developer's time and
workload.
All of these dialog box control classes inherit from the CommonDialog class and override
theRunDialog()functionofthebaseclasstocreatethespecificdialogbox.
The RunDialog() function is automatically invoked when a user of a dialog box calls its
ShowDialog()function.
TheShowDialogmethodisusedtodisplayallthedialogboxcontrolsatruntime.Itreturns
avalueofthetypeofDialogResultenumeration.ThevaluesofDialogResultenumeration
are:
AbortreturnsDialogResult.Abortvalue,whenuserclicksanAbortbutton.
CancelreturnsDialogResult.Cancel,whenuserclicksaCancelbutton.
IgnorereturnsDialogResult.Ignore,whenuserclicksanIgnorebutton.
NoreturnsDialogResult.No,whenuserclicksaNobutton.
Nonereturnsnothingandthedialogboxcontinuesrunning.
OKreturnsDialogResult.OK,whenuserclicksanOKbutton
RetryreturnsDialogResult.Retry,whenuserclicksanRetrybutton
YesreturnsDialogResult.Yes,whenuserclicksanYesbutton
Thefollowingdiagramshowsthecommondialogclassinheritance:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 91/158
23/09/2016 VB.NetQuickGuide
Alltheseabovementionedclasseshavecorrespondingcontrolsthatcouldbeaddedfromthe
Toolbox during design time. You can include relevant functionality of these classes to your
application,eitherbyinstantiatingtheclassprogrammaticallyorbyusingrelevantcontrols.
Whenyoudoubleclickanyofthedialogcontrolsinthetoolboxordragthecontrolontothe
form,itappearsintheComponenttrayatthebottomoftheWindowsFormsDesigner,they
donotdirectlyshowupontheform.
Thefollowingtableliststhecommonlyuseddialogboxcontrols.Clickthefollowinglinksto
checktheirdetail:
S.N. Control&Description
1 ColorDialog
Itrepresentsacommondialogboxthatdisplaysavailablecolorsalongwithcontrols
thatenabletheusertodefinecustomcolors.
2 FontDialog
It prompts the user to choose a font from among those installed on the local
computerandletstheuserselectthefont,fontsize,andcolor.
3 OpenFileDialog
Itpromptstheusertoopenafileandallowstheusertoselectafiletoopen.
4 SaveFileDialog
It prompts the user to select a location for saving a file and allows the user to
specifythenameofthefiletosavedata.
5 PrintDialog
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 92/158
23/09/2016 VB.NetQuickGuide
It lets the user to print documents by selecting a printer and choosing which
sectionsofthedocumenttoprintfromaWindowsFormsapplication.
VB.NetAdvancedForm
Inthischapter,letusstudythefollowingconcepts:
Addingmenusandsubmenusinanapplication
Addingthecut,copyandpastefunctionalitiesinaform
Anchoringanddockingcontrolsinaform
Modalforms
AddingMenusandSubMenusinanApplication
Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were used for
addingmenus,submenusandcontextmenusinaWindowsapplication.
Letuscreateatypicalwindowsmainmenubarandsubmenususingtheoldversioncontrols
firstsincethesecontrolsarestillmuchusedinoldapplications.
Followingisanexample,whichshowshowwecreateamenubarwithmenuitems:File,Edit,
ViewandProject.TheFilemenuhasthesubmenusNew,OpenandSave.
Let'sdoubleclickontheFormandputthefollowingcodeintheopenedwindow.
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'definingthemainmenubar
DimmnuBarAsNewMainMenu()
'definingthemenuitemsforthemainmenubar
DimmyMenuItemFileAsNewMenuItem("&File")
DimmyMenuItemEditAsNewMenuItem("&Edit")
DimmyMenuItemViewAsNewMenuItem("&View")
DimmyMenuItemProjectAsNewMenuItem("&Project")
'addingthemenuitemstothemainmenubar
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 93/158
23/09/2016 VB.NetQuickGuide
'definingsomesubmenus
DimmyMenuItemNewAsNewMenuItem("&New")
DimmyMenuItemOpenAsNewMenuItem("&Open")
DimmyMenuItemSaveAsNewMenuItem("&Save")
'addsubmenustotheFilemenu
myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)
'addthemainmenutotheform
Me.Menu=mnuBar
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
EndClass
WhentheabovecodeisexecutedandrunusingStartbuttonavailableattheMicrosoftVisual
Studiotoolbar,itwillshowthefollowingwindow:
Windows Forms contain a rich set of classes for creating your own custom menus with
modern appearance, look and feel. The MenuStrip, ToolStripMenuItem,
ContextMenuStripcontrolsareusedtocreatemenubarsandcontextmenusefficiently.
Clickthefollowinglinkstochecktheirdetails:
S.N. Control&Description
1 MenuStrip
Itprovidesamenusystemforaform.
2 ToolStripMenuItem
ItrepresentsaselectableoptiondisplayedonaMenuStriporContextMenuStrip.
The ToolStripMenuItem control replaces and adds functionality to the MenuItem
controlofpreviousversions.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 94/158
23/09/2016 VB.NetQuickGuide
2 ContextMenuStrip
Itrepresentsashortcutmenu.
AddingtheCut,CopyandPasteFunctionalitiesinaForm
ThemethodsexposedbytheClipBoardclassareusedforaddingthecut,copyandpaste
functionalitiesinanapplication.TheClipBoardclassprovidesmethodstoplacedataonand
retrievedatafromthesystemClipboard.
Ithasthefollowingcommonlyusedmethods:
S.N MethodName&Description
1 Clear
RemovesalldatafromtheClipboard.
2 ContainsData
IndicateswhetherthereisdataontheClipboardthatisinthespecifiedformatorcan
beconvertedtothatformat.
3 ContainsImage
IndicateswhetherthereisdataontheClipboardthatisintheBitmapformatorcan
beconvertedtothatformat.
4 ContainsText
IndicateswhetherthereisdataontheClipboardintheTextorUnicodeTextformat,
dependingontheoperatingsystem.
5 GetData
RetrievesdatafromtheClipboardinthespecifiedformat.
6 GetDataObject
RetrievesthedatathatiscurrentlyonthesystemClipboard.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 95/158
23/09/2016 VB.NetQuickGuide
7 GetImage
RetrievesanimagefromtheClipboard.
8 GetText
RetrievestextdatafromtheClipboardintheTextorUnicodeTextformat,depending
ontheoperatingsystem.
9 GetText(TextDataFormat)
Retrieves text data from the Clipboard in the format indicated by the specified
TextDataFormatvalue.
10 SetData
ClearstheClipboardandthenaddsdatainthespecifiedformat.
11 SetText(String)
Clears the Clipboard and then adds text data in the Text or UnicodeText format,
dependingontheoperatingsystem.
Followingisanexample,whichshowshowwecut,copyandpastedatausingmethodsofthe
Clipboardclass.Takethefollowingsteps:
Addarichtextboxcontrolandthreebuttoncontrolsontheform.
ChangethetextpropertyofthebuttonstoCut,CopyandPaste,respectively.
Doubleclickonthebuttonstoaddthefollowingcodeinthecodeeditor:
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)_
HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)_
HandlesButton1.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
RichTextBox1.SelectedText=""
EndSub
PrivateSubButton2_Click(senderAsObject,eAsEventArgs)_
HandlesButton2.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 96/158
23/09/2016 VB.NetQuickGuide
EndSub
PrivateSubButton3_Click(senderAsObject,eAsEventArgs)_
HandlesButton3.Click
DimiDataAsIDataObject
iData=Clipboard.GetDataObject()
If(iData.GetDataPresent(DataFormats.Text))Then
RichTextBox1.SelectedText=iData.GetData(DataFormats.Text)
Else
RichTextBox1.SelectedText=""
EndIf
EndSub
EndClass
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
Entersometextandcheckhowthebuttonswork.
AnchoringandDockingControlsinaForm
Anchoringallowsyoutosetananchorpositionforacontroltotheedgesofitscontainer
control,forexample,theform.TheAnchorpropertyoftheControlclassallowsyoutoset
valuesofthisproperty.TheAnchorpropertygetsorsetstheedgesofthecontainertowhich
acontrolisboundanddetermineshowacontrolisresizedwithitsparent.
Whenyouanchoracontroltoaform,thecontrolmaintainsitsdistancefromtheedgesof
theformanditsanchoredposition,whentheformisresized.
YoucansettheAnchorpropertyvaluesofacontrolfromthePropertieswindow:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 97/158
23/09/2016 VB.NetQuickGuide
Forexample,letusaddaButtoncontrolonaformandsetitsanchorpropertytoBottom,
Right. Run this form to see the original position of the Button control with respect to the
form.
Now, when you stretch the form, the distance between the Button and the bottom right
corneroftheformremainssame.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 98/158
23/09/2016 VB.NetQuickGuide
Dockingofacontrolmeansdockingittooneoftheedgesofitscontainer.Indocking,the
controlfillscertainareaofthecontainercompletely.
The Dock property of the Control class does this. The Dock property gets or sets which
controlbordersaredockedtoitsparentcontrolanddetermineshowacontrolisresizedwith
itsparent.
YoucansettheDockpropertyvaluesofacontrolfromthePropertieswindow:
Forexample,letusaddaButtoncontrolonaformandsetitsDockpropertytoBottom.Run
thisformtoseetheoriginalpositionoftheButtoncontrolwithrespecttotheform.
Now,whenyoustretchtheform,theButtonresizesitselfwiththeform.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 99/158
23/09/2016 VB.NetQuickGuide
ModalForms
Modal Forms are those forms that need to be closed or hidden before you can continue
workingwiththerestoftheapplication.Alldialogboxesaremodalforms.AMessageBoxis
alsoamodalform.
Youcancallamodalformbytwoways:
CallingtheShowDialogmethod
CallingtheShowmethod
Let us take up an example in which we will create a modal form, a dialog box. Take the
followingsteps:
Add a form, Form1 to your application, and add two labels and a button control to
Form1
Changethetextpropertiesofthefirstlabelandthebuttonto'WelcometoTutorials
Point' and 'Enter your Name', respectively. Keep the text properties of the second
labelasblank.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 100/158
23/09/2016 VB.NetQuickGuide
AddanewWindowsForm,Form2,andaddtwobuttons,onelabel,andatextboxto
Form2.
ChangethetextpropertiesofthebuttonstoOKandCancel,respectively.Changethe
textpropertiesofthelabelto'Enteryourname:'.
SettheFormBorderStylepropertyofForm2toFixedDialog,forgivingitadialogbox
border.
SettheControlBoxpropertyofForm2toFalse.
SettheShowInTaskbarpropertyofForm2toFalse.
Set the DialogResult property of the OK button to OK and the Cancel button to
Cancel.
AddthefollowingcodesnippetsintheForm2_LoadmethodofForm2:
PrivateSubForm2_Load(senderAsObject,eAsEventArgs)_
HandlesMyBase.Load
AcceptButton=Button1
CancelButton=Button2
EndSub
AddthefollowingcodesnippetsintheButton1_ClickmethodofForm1:
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)_
HandlesButton1.Click
DimfrmSecondAsForm2=NewForm2()
IffrmSecond.ShowDialog()=DialogResult.OKThen
Label2.Text=frmSecond.TextBox1.Text
EndIf
EndSub
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 101/158
23/09/2016 VB.NetQuickGuide
Clickingonthe'EnteryourName'buttondisplaysthesecondform:
ClickingontheOKbuttontakesthecontrolandinformationbackfromthemodalformtothe
previousform:
VB.NetEventHandling
Eventsarebasicallyauseractionlikekeypress,clicks,mousemovements,etc.,orsome
occurrencelikesystemgeneratednotifications.Applicationsneedtorespondtoeventswhen
theyoccur.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 102/158
23/09/2016 VB.NetQuickGuide
Clickingonabutton,orenteringsometextinatextbox,orclickingonamenuitem,allare
examplesofevents.Aneventisanactionthatcallsafunctionormaycauseanotherevent.
Eventhandlersarefunctionsthattellhowtorespondtoanevent.
VB.Netisaneventdrivenlanguage.Therearemainlytwotypesofevents:
Mouseevents
Keyboardevents
HandlingMouseEvents
Mouseeventsoccurwithmousemovementsinformsandcontrols.Followingarethevarious
mouseeventsrelatedwithaControlclass:
MouseDownitoccurswhenamousebuttonispressed
MouseEnteritoccurswhenthemousepointerentersthecontrol
MouseHoveritoccurswhenthemousepointerhoversoverthecontrol
MouseLeaveitoccurswhenthemousepointerleavesthecontrol
MouseMoveitoccurswhenthemousepointermovesoverthecontrol
MouseUp it occurs when the mouse pointer is over the control and the mouse
buttonisreleased
MouseWheelitoccurswhenthemousewheelmovesandthecontrolhasfocus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgsobjectisusedforhandlingmouseevents.Ithasthefollowingproperties:
Buttonsindicatesthemousebuttonpressed
Clicksindicatesthenumberofclicks
Deltaindicatesthenumberofdetentsthemousewheelrotated
Xindicatesthexcoordinateofmouseclick
Yindicatestheycoordinateofmouseclick
Example
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 103/158
23/09/2016 VB.NetQuickGuide
Following is an example, which shows how to handle mouse events. Take the following
steps:
Addthreelabels,threetextboxesandabuttoncontrolintheform.
Change the text properties of the labels to Customer ID, Name and Address,
respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress,
respectively.
Changethetextpropertyofthebuttonto'Submit'.
Addthefollowingcodeinthecodeeditorwindow:
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspont.com"
EndSub
PrivateSubtxtID_MouseEnter(senderAsObject,eAsEventArgs)_
HandlestxtID.MouseEnter
'codeforhandlingmouseenteronIDtextbox
txtID.BackColor=Color.CornflowerBlue
txtID.ForeColor=Color.White
EndSub
PrivateSubtxtID_MouseLeave(senderAsObject,eAsEventArgs)_
HandlestxtID.MouseLeave
'codeforhandlingmouseleaveonIDtextbox
txtID.BackColor=Color.White
txtID.ForeColor=Color.Blue
EndSub
PrivateSubtxtName_MouseEnter(senderAsObject,eAsEventArgs)_
HandlestxtName.MouseEnter
'codeforhandlingmouseenteronNametextbox
txtName.BackColor=Color.CornflowerBlue
txtName.ForeColor=Color.White
EndSub
PrivateSubtxtName_MouseLeave(senderAsObject,eAsEventArgs)_
HandlestxtName.MouseLeave
'codeforhandlingmouseleaveonNametextbox
txtName.BackColor=Color.White
txtName.ForeColor=Color.Blue
EndSub
PrivateSubtxtAddress_MouseEnter(senderAsObject,eAsEventArgs)_
HandlestxtAddress.MouseEnter
'codeforhandlingmouseenteronAddresstextbox
txtAddress.BackColor=Color.CornflowerBlue
txtAddress.ForeColor=Color.White
EndSub
PrivateSubtxtAddress_MouseLeave(senderAsObject,eAsEventArgs)_
HandlestxtAddress.MouseLeave
'codeforhandlingmouseleaveonAddresstextbox
txtAddress.BackColor=Color.White
txtAddress.ForeColor=Color.Blue
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 104/158
23/09/2016 VB.NetQuickGuide
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)_
HandlesButton1.Click
MsgBox("Thankyou"&txtName.Text&",foryourkindcooperation")
EndSub
EndClass
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
Trytoentertextinthetextboxesandcheckthemouseevents:
HandlingKeyboardEvents
FollowingarethevariouskeyboardeventsrelatedwithaControlclass:
KeyDownoccurswhenakeyispresseddownandthecontrolhasfocus
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 105/158
23/09/2016 VB.NetQuickGuide
KeyPressoccurswhenakeyispressedandthecontrolhasfocus
KeyUpoccurswhenakeyisreleasedwhilethecontrolhasfocus
The event handlers of the KeyDown and KeyUp events get an argument of type
KeyEventArgs.Thisobjecthasthefollowingproperties:
AltitindicateswhethertheALTkeyispressed/p>
ControlitindicateswhethertheCTRLkeyispressed
Handleditindicateswhethertheeventishandled
KeyCodestoresthekeyboardcodefortheevent
KeyDatastoresthekeyboarddatafortheevent
KeyValuestoresthekeyboardvaluefortheevent
Modifiersitindicateswhichmodifierkeys(Ctrl,Shift,and/orAlt)arepressed
ShiftitindicatesiftheShiftkeyispressed
The event handlers of the KeyDown and KeyUp events get an argument of type
KeyEventArgs.Thisobjecthasthefollowingproperties:
HandledindicatesiftheKeyPresseventishandled
KeyCharstoresthecharactercorrespondingtothekeypressed
Example
Letuscontinuewiththepreviousexampletoshowhowtohandlekeyboardevents.Thecode
willverifythattheuserenterssomenumbersforhiscustomerIDandage.
Add a label with text Property as 'Age' and add a corresponding text box named
txtAge.
AddthefollowingcodesforhandlingtheKeyUPeventsofthetextboxtxtID.
PrivateSubtxtID_KeyUP(senderAsObject,eAsKeyEventArgs)_
HandlestxtID.KeyUp
If(NotChar.IsNumber(ChrW(e.KeyCode)))Then
MessageBox.Show("EnternumbersforyourCustomerID")
txtID.Text=""
EndIf
EndSub
AddthefollowingcodesforhandlingtheKeyUPeventsofthetextboxtxtID.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 106/158
23/09/2016 VB.NetQuickGuide
PrivateSubtxtAge_KeyUP(senderAsObject,eAsKeyEventArgs)_
HandlestxtAge.KeyUp
If(NotChar.IsNumber(ChrW(e.keyCode)))Then
MessageBox.Show("Enternumbersforage")
txtAge.Text=""
EndIf
EndSub
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
If you leave the text for age or ID as blank or enter some nonnumeric data, it gives a
warningmessageboxandclearstherespectivetext:
VB.NetRegularExpressions
A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching. A pattern
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 107/158
23/09/2016 VB.NetQuickGuide
consistsofoneormorecharacterliterals,operators,orconstructs.
ConstructsforDefiningRegularExpressions
Therearevariouscategoriesofcharacters,operators,andconstructsthatletsyoutodefine
regularexpressions.Clickthefollwoinglinkstofindtheseconstructs.
Characterescapes
Characterclasses
Anchors
Groupingconstructs
Quantifiers
Backreferenceconstructs
Alternationconstructs
Substitutions
Miscellaneousconstructs
TheRegexClass
TheRegexclassisusedforrepresentingaregularexpression.
TheRegexclasshasthefollowingcommonlyusedmethods:
S.N Methods&Description
1 PublicFunctionIsMatch(inputAsString)AsBoolean
IndicateswhethertheregularexpressionspecifiedintheRegexconstructorfindsa
matchinaspecifiedinputstring.
2 PublicFunctionIsMatch(inputAsString,startatAsInteger)AsBoolean
IndicateswhethertheregularexpressionspecifiedintheRegexconstructorfindsa
matchinthespecifiedinputstring,beginningatthespecifiedstartingpositioninthe
string.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 108/158
23/09/2016 VB.NetQuickGuide
Indicates whether the specified regular expression finds a match in the specified
inputstring.
4 PublicFunctionMatches(inputAsString)AsMatchCollection
Searchesthespecifiedinputstringforalloccurrencesofaregularexpression.
5 PublicFunctionReplace(inputAsString,replacementAsString)AsString
In a specified input string, replaces all strings that match a regular expression
patternwithaspecifiedreplacementstring.
6 PublicFunctionSplit(inputAsString)AsString()
Splitsaninputstringintoanarrayofsubstringsatthepositionsdefinedbyaregular
expressionpatternspecifiedintheRegexconstructor.
Forthecompletelistofmethodsandproperties,pleaseconsultMicrosoftdocumentation.
Example1
Thefollowingexamplematcheswordsthatstartwith'S':
ImportsSystem.Text.RegularExpressions
ModuleregexProg
SubshowMatch(ByValtextAsString,ByValexprAsString)
Console.WriteLine("TheExpression:"+expr)
DimmcAsMatchCollection=Regex.Matches(text,expr)
DimmAsMatch
ForEachmInmc
Console.WriteLine(m)
Nextm
EndSub
SubMain()
DimstrAsString="AThousandSplendidSuns"
Console.WriteLine("Matchingwordsthatstartwith'S':")
showMatch(str,"\bS\S*")
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 109/158
23/09/2016 VB.NetQuickGuide
Matchingwordsthatstartwith'S':
TheExpression:\bS\S*
Splendid
Suns
Example2
Thefollowingexamplematcheswordsthatstartwith'm'andendswith'e':
ImportsSystem.Text.RegularExpressions
ModuleregexProg
SubshowMatch(ByValtextAsString,ByValexprAsString)
Console.WriteLine("TheExpression:"+expr)
DimmcAsMatchCollection=Regex.Matches(text,expr)
DimmAsMatch
ForEachmInmc
Console.WriteLine(m)
Nextm
EndSub
SubMain()
DimstrAsString="makeamazeandmanagetomeasureit"
Console.WriteLine("Matchingwordsthatstartwith'm'andendswith'e':")
showMatch(str,"\bm\S*e\b")
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Matchingwordsstartwith'm'andendswith'e':
TheExpression:\bm\S*e\b
make
maze
manage
measure
Example3
Thisexamplereplacesextrawhitespace:
ImportsSystem.Text.RegularExpressions
ModuleregexProg
SubMain()
DiminputAsString="HelloWorld"
DimpatternAsString="\\s+"
DimreplacementAsString=""
DimrgxAsRegex=NewRegex(pattern)
DimresultAsString=rgx.Replace(input,replacement)
Console.WriteLine("OriginalString:{0}",input)
Console.WriteLine("ReplacementString:{0}",result)
Console.ReadKey()
EndSub
EndModule
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 110/158
23/09/2016 VB.NetQuickGuide
OriginalString:HelloWorld
ReplacementString:HelloWorld
VB.NetDatabaseAccess
Applications communicate with a database, firstly, to retrieve the data stored there and
present it in a userfriendly way, and secondly, to update the database by inserting,
modifyinganddeletingdata.
MicrosoftActiveXDataObjects.Net(ADO.Net)isamodel,apartofthe.Netframeworkthat
isusedbythe.Netapplicationsforretrieving,accessingandupdatingdata.
ADO.NetObjectModel
ADO.Net object model is nothing but the structured process flow through various
components.Theobjectmodelcanbepictoriallydescribedas:
Thedataresidinginadatastoreordatabaseisretrievedthroughthedataprovider.Various
componentsofthedataproviderretrievedatafortheapplicationandupdatedata.
Anapplicationaccessesdataeitherthroughadatasetoradatareader.
Datasetsstoredatainadisconnectedcacheandtheapplicationretrievesdatafrom
it.
Datareadersprovidedatatotheapplicationinareadonlyandforwardonlymode.
DataProvider
A data provider is used for connecting to a database, executing commands and retrieving
data,storingitinadataset,readingtheretrieveddataandupdatingthedatabase.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 111/158
23/09/2016 VB.NetQuickGuide
ThedataproviderinADO.Netconsistsofthefollowingfourobjects:
S.N Objects&Description
1 Connection
Thiscomponentisusedtosetupaconnectionwithadatasource.
2 Command
AcommandisaSQLstatementorastoredprocedureusedtoretrieve,insert,delete
ormodifydatainadatasource.
3 DataReader
Datareaderisusedtoretrievedatafromadatasourceinareadonlyandforward
onlymode.
4 DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a
databasethroughadataadapter.Itretrievesdatafromadatabaseintoadataset
andupdatesthedatabase.Whenchangesaremadetothedataset,thechangesin
thedatabaseareactuallydonebythedataadapter.
TherearefollowingdifferenttypesofdataprovidersincludedinADO.Net
The.NetFrameworkdataproviderforSQLServerprovidesaccesstoMicrosoftSQL
Server.
The .Net Framework data provider for OLE DB provides access to data sources
exposedbyusingOLEDB.
The .Net Framework data provider for ODBC provides access to data sources
exposedbyODBC.
The .Net Framework data provider for Oracle provides access to Oracle data
source.
TheEntityClientproviderenablesaccessingdatathroughEntityDataModel(EDM)
applications.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 112/158
23/09/2016 VB.NetQuickGuide
DataSet
DataSetisaninmemoryrepresentationofdata.Itisadisconnected,cachedsetofrecords
thatareretrievedfromadatabase.Whenaconnectionisestablishedwiththedatabase,the
dataadaptercreatesadatasetandstoresdatainit.Afterthedataisretrievedandstoredin
a dataset, the connection with the database is closed. This is called the 'disconnected
architecture'.Thedatasetworksasavirtualdatabasecontainingtables,rows,andcolumns.
Thefollowingdiagramshowsthedatasetobjectmodel:
TheDataSetclassispresentintheSystem.Datanamespace.Thefollowingtabledescribes
allthecomponentsofDataSet:
S.N Components&Description
1 DataTableCollection
Itcontainsallthetablesretrievedfromthedatasource.
2 DataRelationCollection
Itcontainsrelationshipsandthelinksbetweentablesinadataset.
3 ExtendedProperties
Itcontainsadditionalinformation,liketheSQLstatementforretrievingdata,timeof
retrieval,etc.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 113/158
23/09/2016 VB.NetQuickGuide
4 DataTable
5 DataRelation
6 DataRowCollection
ItcontainsalltherowsinaDataTable.
7 DataView
ItrepresentsafixedcustomizedviewofaDataTableforsorting,filtering,searching,
editingandnavigation.
8 PrimaryKey
ItrepresentsthecolumnthatuniquelyidentifiesarowinaDataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and
methods are used to retrieve, evaluate, insert, delete, and update values in the
DataTable.TheNewRowmethodisusedtocreateanewrowandtheAddmethod
addsarowtothetable.
10 DataColumnCollection
ItrepresentsallthecolumnsinaDataTable.
11 DataColumn
ItconsistsofthenumberofcolumnsthatcompriseaDataTable.
ConnectingtoaDatabase
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 114/158
23/09/2016 VB.NetQuickGuide
The.NetFrameworkprovidestwotypesofConnectionclasses:
SqlConnectiondesignedforconnectingtoMicrosoftSQLServer.
Example1
We have a table stored in Microsoft SQL Server, named Customers, in a database named
testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in
SQLServer.
Letusconnecttothisdatabase.Takethefollowingsteps:
SelectTOOLS>ConnecttoDatabase
SelectaservernameandthedatabasenameintheAddConnectiondialogbox.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 115/158
23/09/2016 VB.NetQuickGuide
ClickontheTestConnectionbuttontocheckiftheconnectionsucceeded.
AddaDataGridViewontheform.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 116/158
23/09/2016 VB.NetQuickGuide
ClickontheChooseDataSourcecombobox.
ClickontheAddProjectDataSourcelink.
ThisopenstheDataSourceConfigurationWizard.
SelectDatabaseasthedatasourcetype
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 117/158
23/09/2016 VB.NetQuickGuide
ChooseDataSetasthedatabasemodel.
Choosetheconnectionalreadysetup.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 118/158
23/09/2016 VB.NetQuickGuide
Savetheconnectionstring.
Choose the database object, Customers table in our example, and click the Finish
button.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 119/158
23/09/2016 VB.NetQuickGuide
SelectthePreviewDatalinktoseethedataintheResultsgrid:
WhentheapplicationisrunusingStartbuttonavailableattheMicrosoftVisualStudiotool
bar,itwillshowthefollowingwindow:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 120/158
23/09/2016 VB.NetQuickGuide
Example2
Inthisexample,letusaccessdatainaDataGridViewcontrolusingcode.Takethefollowing
steps:
AddaDataGridViewcontrolandabuttonintheform.
Changethetextofthebuttoncontrolto'Fill'.
Double click the button control to add the required code for the Click event of the
button,asshownbelow:
ImportsSystem.Data.SqlClient
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)_
HandlesMyBase.Load
'TODO:Thislineofcodeloadsdataintothe'TestDBDataSet.CUSTOMERS'table.Youcanmove,orr
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
DimconnectionAsSqlConnection=Newsqlconnection()
connection.ConnectionString="DataSource=KABIRDESKTOP;_
InitialCatalog=testDB;IntegratedSecurity=True"
connection.Open()
DimadpAsSqlDataAdapter=NewSqlDataAdapter_
("select*fromCustomers",connection)
DimdsAsDataSet=NewDataSet()
adp.Fill(ds)
DataGridView1.DataSource=ds.Tables(0)
EndSub
EndClass
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 121/158
23/09/2016 VB.NetQuickGuide
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
ClickingtheFillbuttondisplaysthetableonthedatagridviewcontrol:
CreatingTable,ColumnsandRows
WehavediscussedthattheDataSetcomponentslikeDataTable,DataColumnandDataRow
allowustocreatetables,columnsandrows,respectively.
Thefollowingexampledemonstratestheconcept:
Example3
So far, we have used tables and databases already existing in our computer. In this
example, we will create a table, add columns, rows and data into it and display the table
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 122/158
23/09/2016 VB.NetQuickGuide
usingaDataGridViewobject.
Takethefollowingsteps:
AddaDataGridViewcontrolandabuttonintheform.
Changethetextofthebuttoncontrolto'Fill'.
Addthefollowingcodeinthecodeeditor.
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspont.com"
EndSub
PrivateFunctionCreateDataSet()AsDataSet
'creatingaDataSetobjectfortables
DimdatasetAsDataSet=NewDataSet()
'creatingthestudenttable
DimStudentsAsDataTable=CreateStudentTable()
dataset.Tables.Add(Students)
Returndataset
EndFunction
PrivateFunctionCreateStudentTable()AsDataTable
DimStudentsAsDataTable
Students=NewDataTable("Student")
'addingcolumns
AddNewColumn(Students,"System.Int32","StudentID")
AddNewColumn(Students,"System.String","StudentName")
AddNewColumn(Students,"System.String","StudentCity")
'addingrows
AddNewRow(Students,1,"ZaraAli","Kolkata")
AddNewRow(Students,2,"ShreyaSharma","Delhi")
AddNewRow(Students,3,"RiniMukherjee","Hyderabad")
AddNewRow(Students,4,"SunilDubey","Bikaner")
AddNewRow(Students,5,"RajatMishra","Patna")
ReturnStudents
EndFunction
PrivateSubAddNewColumn(ByReftableAsDataTable,_
ByValcolumnTypeAsString,ByValcolumnNameAsString)
DimcolumnAsDataColumn=_
table.Columns.Add(columnName,Type.GetType(columnType))
EndSub
'addingdataintothetable
PrivateSubAddNewRow(ByReftableAsDataTable,ByRefidAsInteger,_
ByRefnameAsString,ByRefcityAsString)
DimnewrowAsDataRow=table.NewRow()
newrow("StudentID")=id
newrow("StudentName")=name
newrow("StudentCity")=city
table.Rows.Add(newrow)
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
DimdsAsNewDataSet
ds=CreateDataSet()
DataGridView1.DataSource=ds.Tables("Student")
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 123/158
23/09/2016 VB.NetQuickGuide
EndSub
EndClass
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
ClickingtheFillbuttondisplaysthetableonthedatagridviewcontrol:
VB.NetExcelSheet
VB.Net provides support for interoperability between the COM object model of Microsoft
Excel2010andyourapplication.
To avail this interoperability in your application, you need to import the namespace
Microsoft.Office.Interop.ExcelinyourWindowsFormApplication.
CreatinganExcelApplicationfromVB.Net
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 124/158
23/09/2016 VB.NetQuickGuide
Let's start with creating a Window Forms Application by following the following steps in
MicrosoftVisualStudio:File>NewProject>WindowsFormsApplications
Finally,selectOK,MicrosoftVisualStudiocreatesyourprojectanddisplaysfollowingForm1.
InsertaButtoncontrolButton1intheform.
AddareferencetoMicrosoftExcelObjectLibrarytoyourproject.Todothis:
SelectAddReferencefromtheProjectMenu.
OntheCOMtab,locateMicrosoftExcelObjectLibraryandthenclickSelect.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 125/158
23/09/2016 VB.NetQuickGuide
ClickOK.
DoubleclickthecodewindowandpopulatetheClickeventofButton1,asshownbelow.
'AddthefollowingcodesnippetontopofForm1.vb
ImportsExcel=Microsoft.Office.Interop.Excel
PublicClassForm1
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
DimappXLAsExcel.Application
DimwbXlAsExcel.Workbook
DimshXLAsExcel.Worksheet
DimraXLAsExcel.Range
'StartExcelandgetApplicationobject.
appXL=CreateObject("Excel.Application")
appXL.Visible=True
'Addanewworkbook.
wbXl=appXL.Workbooks.Add
shXL=wbXl.ActiveSheet
'Addtableheadersgoingcellbycell.
shXL.Cells(1,1).Value="FirstName"
shXL.Cells(1,2).Value="LastName"
shXL.Cells(1,3).Value="FullName"
shXL.Cells(1,4).Value="Specialization"
'FormatA1:D1asbold,verticalalignment=center.
WithshXL.Range("A1","D1")
.Font.Bold=True
.VerticalAlignment=Excel.XlVAlign.xlVAlignCenter
EndWith
'Createanarraytosetmultiplevaluesatonce.
Dimstudents(5,2)AsString
students(0,0)="Zara"
students(0,1)="Ali"
students(1,0)="Nuha"
students(1,1)="Ali"
students(2,0)="Arilia"
students(2,1)="RamKumar"
students(3,0)="Rita"
students(3,1)="Jones"
students(4,0)="Umme"
students(4,1)="Ayman"
'FillA2:B6withanarrayofvalues(FirstandLastNames).
shXL.Range("A2","B6").Value=students
'FillC2:C6witharelativeformula(=A2&""&B2).
raXL=shXL.Range("C2","C6")
raXL.Formula="=A2&""""&B2"
'FillD2:D6values.
WithshXL
.Cells(2,4).Value="Biology"
.Cells(3,4).Value="Mathmematics"
.Cells(4,4).Value="Physics"
.Cells(5,4).Value="Mathmematics"
.Cells(6,4).Value="Arabic"
EndWith
'AutoFitcolumnsA:D.
raXL=shXL.Range("A1","D1")
raXL.EntireColumn.AutoFit()
'MakesureExcelisvisibleandgivetheusercontrol
'ofExcel'slifetime.
appXL.Visible=True
appXL.UserControl=True
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 126/158
23/09/2016 VB.NetQuickGuide
'Releaseobjectreferences.
raXL=Nothing
shXL=Nothing
wbXl=Nothing
appXL.Quit()
appXL=Nothing
ExitSub
Err_Handler:
MsgBox(Err.Description,vbCritical,"Error:"&Err.Number)
EndSub
EndClass
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow:
ClickingontheButtonwoulddisplaythefollowingexcelsheet.Youwillbeaskedtosavethe
workbook.
VB.NetSendEmail
VB.Net allows sending emails from your application. The System.Net.Mail namespace
containsclassesusedforsendingemailstoaSimpleMailTransferProtocol(SMTP)server
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 127/158
23/09/2016 VB.NetQuickGuide
fordelivery.
Thefollowingtablelistssomeofthesecommonlyusedclasses:
1 Attachment Representsanattachmenttoanemail.
2 AttachmentCollection Storesattachmentstobesentaspartofanemailmessage.
3 MailAddress Representstheaddressofanelectronicmailsenderor
recipient.
4 MailAddressCollection Storesemailaddressesthatareassociatedwithanemail
message.
5 MailMessage Representsanemailmessagethatcanbesentusingthe
SmtpClientclass.
6 SmtpClient AllowsapplicationstosendemailbyusingtheSimpleMail
TransferProtocol(SMTP).
7 SmtpException RepresentstheexceptionthatisthrownwhentheSmtpClient
isnotabletocompleteaSendorSendAsyncoperation.
TheSmtpClientClass
The SmtpClient class allows applications to send email by using the Simple Mail Transfer
Protocol(SMTP).
FollowingaresomecommonlyusedpropertiesoftheSmtpClientclass:
1 ClientCertificates Specifieswhichcertificatesshouldbeusedtoestablishthe
SecureSocketsLayer(SSL)connection.
2 Credentials Getsorsetsthecredentialsusedtoauthenticatethesender.
3 EnableSsl SpecifieswhethertheSmtpClientusesSecureSocketsLayer
(SSL)toencrypttheconnection.
4 Host GetsorsetsthenameorIPaddressofthehostusedforSMTP
transactions.
5 Port GetsorsetstheportusedforSMTPtransactions.
6 Timeout Getsorsetsavaluethatspecifiestheamountoftimeafter
whichasynchronousSendcalltimesout.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 128/158
23/09/2016 VB.NetQuickGuide
7 UseDefaultCredentials GetsorsetsaBooleanvaluethatcontrolswhetherthe
DefaultCredentialsaresentwithrequests.
FollowingaresomecommonlyusedmethodsoftheSmtpClientclass:
S.N Method&Description
1 Dispose
SendsaQUITmessagetotheSMTPserver,gracefullyendstheTCPconnection,and
releasesallresourcesusedbythecurrentinstanceoftheSmtpClientclass.
2 Dispose(Boolean)
Sends a QUIT message to the SMTP server, gracefully ends the TCP connection,
releases all resources used by the current instance of the SmtpClient class, and
optionallydisposesofthemanagedresources.
3 OnSendCompleted
RaisestheSendCompletedevent.
4 Send(MailMessage)
SendsthespecifiedmessagetoanSMTPserverfordelivery.
5 Send(String,String,String,String)
Sends the specified email message to an SMTP server for delivery. The message
sender,recipients,subject,andmessagebodyarespecifiedusingStringobjects.
6 SendAsync(MailMessage,Object)
Sends the specified email message to an SMTP server for delivery. This method
does not block the calling thread and allows the caller to pass an object to the
methodthatisinvokedwhentheoperationcompletes.
7 SendAsync(String,String,String,String,Object)
Sends an email message to an SMTP server for delivery. The message sender,
recipients, subject, and message body are specified using String objects. This
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 129/158
23/09/2016 VB.NetQuickGuide
methoddoesnotblockthecallingthreadandallowsthecallertopassanobjectto
themethodthatisinvokedwhentheoperationcompletes.
8 SendAsyncCancel
Cancelsanasynchronousoperationtosendanemailmessage.
9 SendMailAsync(MailMessage)
10 SendMailAsync(String,String,String,String)
11 ToString
Returnsastringthatrepresentsthecurrentobject.
ThefollowingexampledemonstrateshowtosendmailusingtheSmtpClientclass.Following
pointsaretobenotedinthisrespect:
YoumustspecifytheSMTPhostserverthatyouusetosendemail.TheHost and
Port properties will be different for different host server. We will be using gmail
server.
YouneedtogivetheCredentialsforauthentication,ifrequiredbytheSMTPserver.
Youshouldalsoprovidetheemailaddressofthesenderandtheemailaddressor
addresses of the recipients using the MailMessage.From and MailMessage.To
properties,respectively.
You should also specify the message content using the MailMessage.Body
property.
Example
In this example, let us create a simple application that would send an email. Take the
followingsteps:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 130/158
23/09/2016 VB.NetQuickGuide
Addthreelabels,threetextboxesandabuttoncontrolintheform.
Change the text properties of the labels to 'From', 'To:' and 'Message:'
respectively.
Change the name properties of the texts to txtFrom, txtTo and txtMessage
respectively.
Changethetextpropertyofthebuttoncontrolto'Send'
Addthefollowingcodeinthecodeeditor.
ImportsSystem.Net.Mail
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
Try
DimSmtp_ServerAsNewSmtpClient
Dime_mailAsNewMailMessage()
Smtp_Server.UseDefaultCredentials=False
Smtp_Server.Credentials=NewNet.NetworkCredential("username@gmail.com","password")
Smtp_Server.Port=587
Smtp_Server.EnableSsl=True
Smtp_Server.Host="smtp.gmail.com"
e_mail=NewMailMessage()
e_mail.From=NewMailAddress(txtFrom.Text)
e_mail.To.Add(txtTo.Text)
e_mail.Subject="EmailSending"
e_mail.IsBodyHtml=False
e_mail.Body=txtMessage.Text
Smtp_Server.Send(e_mail)
MsgBox("MailSent")
Catcherror_tAsException
MsgBox(error_t.ToString)
EndTry
EndSub
Youmustprovideyourgmailaddressandrealpasswordforcredentials.
When the above code is executed and run using Start button available at the Microsoft
VisualStudiotoolbar,itwillshowthefollowingwindow,whichyouwillusetosendyoure
mails,tryityourself.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 131/158
23/09/2016 VB.NetQuickGuide
VB.NetXMLProcessing
TheExtensibleMarkupLanguage(XML)isamarkuplanguagemuchlikeHTMLorSGML.This
isrecommendedbytheWorldWideWebConsortiumandavailableasanopenstandard.
The System.Xml namespace in the .Net Framework contains classes for processing XML
documents. Following are some of the commonly used classes in the System.Xml
namespace.
<td>XmlUrlResolver
1 XmlAttribute Representsanattribute.Validanddefaultvaluesforthe
attributearedefinedinadocumenttypedefinition(DTD)
orschema.
2 XmlCDataSection RepresentsaCDATAsection.
3 XmlCharacterData Providestextmanipulationmethodsthatareusedby
severalclasses.
4 XmlComment RepresentsthecontentofanXMLcomment.
5 XmlConvert EncodesanddecodesXMLnamesandprovidesmethods
forconvertingbetweencommonlanguageruntimetypes
andXMLSchemadefinitionlanguage(XSD)types.When
convertingdatatypes,thevaluesreturnedarelocale
independent.
6 XmlDeclaration RepresentstheXMLdeclarationnode<?xml
version='1.0'...?>.
7 XmlDictionary ImplementsadictionaryusedtooptimizeWindows
CommunicationFoundation(WCF)'sXMLreader/writer
implementations.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 132/158
23/09/2016 VB.NetQuickGuide
8 XmlDictionaryReader AnabstractclassthattheWindowsCommunication
Foundation(WCF)derivesfromXmlReadertodo
serializationanddeserialization.
9 XmlDictionaryWriter RepresentsanabstractclassthatWindowsCommunication
Foundation(WCF)derivesfromXmlWritertodo
serializationanddeserialization.
10 XmlDocument RepresentsanXMLdocument.
11 XmlDocumentFragment Representsalightweightobjectthatisusefulfortree
insertoperations.
12 XmlDocumentType Representsthedocumenttypedeclaration.
13 XmlElement Representsanelement.
14 XmlEntity Representsanentitydeclaration,suchas<!ENTITY...>.
15 XmlEntityReference Representsanentityreferencenode.
16 XmlException Returnsdetailedinformationaboutthelastexception.
17 XmlImplementation DefinesthecontextforasetofXmlDocumentobjects.
18 XmlLinkedNode Getsthenodeimmediatelyprecedingorfollowingthis
node.
19 XmlNode RepresentsasinglenodeintheXMLdocument.
20 XmlNodeList Representsanorderedcollectionofnodes.
21 XmlNodeReader Representsareaderthatprovidesfast,noncached
forwardonlyaccesstoXMLdatainanXmlNode.
22 XmlNotation Representsanotationdeclaration,suchas<!NOTATION...
>.
23 XmlParserContext Providesallthecontextinformationrequiredbythe
XmlReadertoparseanXMLfragment.
24 XmlProcessingInstruction Representsaprocessinginstruction,whichXMLdefinesto
keepprocessorspecificinformationinthetextofthe
document.
25 XmlQualifiedName RepresentsanXMLqualifiedname.
26 XmlReader Representsareaderthatprovidesfast,noncached,
forwardonlyaccesstoXMLdata.
27 XmlReaderSettings SpecifiesasetoffeaturestosupportontheXmlReader
objectcreatedbytheCreatemethod.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 133/158
23/09/2016 VB.NetQuickGuide
28 XmlResolver ResolvesexternalXMLresourcesnamedbyaUniform
ResourceIdentifier(URI).
29 XmlSecureResolver HelpstosecureanotherimplementationofXmlResolverby
wrappingtheXmlResolverobjectandrestrictingthe
resourcesthattheunderlyingXmlResolverhasaccessto.
30 XmlSignificantWhitespace Representswhitespacebetweenmarkupinamixed
contentnodeorwhitespacewithinanxml:space=
'preserve'scope.Thisisalsoreferredtoassignificant
whitespace.
31 XmlText Representsthetextcontentofanelementorattribute.
32 XmlTextReader Representsareaderthatprovidesfast,noncached,
forwardonlyaccesstoXMLdata.
33 XmlTextWriter Representsawriterthatprovidesafast,noncached,
forwardonlywayofgeneratingstreamsorfilescontaining
XMLdatathatconformstotheW3CExtensibleMarkup
Language(XML)1.0andtheNamespacesinXML
recommendations.
34 ResolvesexternalXML
resourcesnamedbya
UniformResourceIdentifier
(URI).
35 XmlWhitespace Representswhitespaceinelementcontent.
36 XmlWriter Representsawriterthatprovidesafast,noncached,
forwardonlymeansofgeneratingstreamsorfiles
containingXMLdata.
37 XmlWriterSettings SpecifiesasetoffeaturestosupportontheXmlWriter
objectcreatedbytheXmlWriter.Createmethod.
XMLParserAPIs
ThetwomostbasicandbroadlyusedAPIstoXMLdataaretheSAXandDOMinterfaces.
SimpleAPIforXML(SAX):Here,youregistercallbacksforeventsofinterestand
then let the parser proceed through the document. This is useful when your
documentsarelargeoryouhavememorylimitations,itparsesthefileasitreadsit
fromdisk,andtheentirefileisneverstoredinmemory.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 134/158
23/09/2016 VB.NetQuickGuide
Document Object Model (DOM) API : This is World Wide Web Consortium
recommendation wherein the entire file is read into memory and stored in a
hierarchical(treebased)formtorepresentallthefeaturesofanXMLdocument.
SAXobviouslycan'tprocessinformationasfastasDOMcanwhenworkingwithlargefiles.
Ontheotherhand,usingDOMexclusivelycanreallykillyourresources,especiallyifusedon
alotofsmallfiles.
SAXisreadonly,whileDOMallowschangestotheXMLfile.SincethesetwodifferentAPIs
literally complement each other there is no reason why you can't use them both for large
projects.
ForallourXMLcodeexamples,let'suseasimpleXMLfilemovies.xmlasaninput:
<?xmlversion="1.0"?>
<collectionshelf="NewArrivals">
<movietitle="EnemyBehind">
<type>War,Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>TalkaboutaUSJapanwar</description>
</movie>
<movietitle="Transformers">
<type>Anime,ScienceFiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>Aschientificfiction</description>
</movie>
<movietitle="Trigun">
<type>Anime,Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>VashtheStampede!</description>
</movie>
<movietitle="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewableboredom</description>
</movie>
</collection>
ParsingXMLwithSAXAPI
InSAXmodel,youusetheXmlReaderandXmlWriterclassestoworkwiththeXMLdata.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 135/158
23/09/2016 VB.NetQuickGuide
The XmlReader class is used to read XML data in a fast, forwardonly and noncached
manner.ItreadsanXMLdocumentorastream.
Example1
ThisexampledemonstratesreadingXMLdatafromthefilemovies.xml.
Takethefollowingsteps:
Addthemovies.xmlfileinthebin\Debugfolderofyourapplication.
ImporttheSystem.XmlnamespaceinForm1.vbfile.
Addalabelintheformandchangeitstextto'MoviesGalore'.
Add three list boxes and three buttons to show the title, type and description of a
moviefromthexmlfile.
Addthefollowingcodeusingthecodeeditorwindow.
ImportsSystem.Xml
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
ListBox1().Items.Clear()
DimxrAsXmlReader=XmlReader.Create("movies.xml")
DoWhilexr.Read()
Ifxr.NodeType=XmlNodeType.ElementAndAlsoxr.Name="movie"Then
ListBox1.Items.Add(xr.GetAttribute(0))
EndIf
Loop
EndSub
PrivateSubButton2_Click(senderAsObject,eAsEventArgs)HandlesButton2.Click
ListBox2().Items.Clear()
DimxrAsXmlReader=XmlReader.Create("movies.xml")
DoWhilexr.Read()
Ifxr.NodeType=XmlNodeType.ElementAndAlsoxr.Name="type"Then
ListBox2.Items.Add(xr.ReadElementString)
Else
xr.Read()
EndIf
Loop
EndSub
PrivateSubButton3_Click(senderAsObject,eAsEventArgs)HandlesButton3.Click
ListBox3().Items.Clear()
DimxrAsXmlReader=XmlReader.Create("movies.xml")
DoWhilexr.Read()
Ifxr.NodeType=XmlNodeType.ElementAndAlsoxr.Name="description"Then
ListBox3.Items.Add(xr.ReadElementString)
Else
xr.Read()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 136/158
23/09/2016 VB.NetQuickGuide
EndIf
Loop
EndSub
EndClass
ExecuteandruntheabovecodeusingStartbuttonavailableattheMicrosoftVisualStudio
toolbar.Clickingonthebuttonswoulddisplay,title,typeanddescriptionofthemoviesfrom
thefile.
TheXmlWriterclassisusedtowriteXMLdataintoastream,afileoraTextWriterobject.It
alsoworksinaforwardonly,noncachedmanner.
Example2
LetuscreateanXMLfilebyaddingsomedataatruntime.Takethefollowingsteps:
AddaWebBrowsercontrolandabuttoncontrolintheform.
ChangetheTextpropertyofthebuttontoShowAuthorsFile.
Addthefollowingcodeinthecodeeditor.
ImportsSystem.Xml
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
DimxwsAsXmlWriterSettings=NewXmlWriterSettings()
xws.Indent=True
xws.NewLineOnAttributes=True
DimxwAsXmlWriter=XmlWriter.Create("authors.xml",xws)
xw.WriteStartDocument()
xw.WriteStartElement("Authors")
xw.WriteStartElement("author")
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 137/158
23/09/2016 VB.NetQuickGuide
xw.WriteAttributeString("code","1")
xw.WriteElementString("fname","Zara")
xw.WriteElementString("lname","Ali")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code","2")
xw.WriteElementString("fname","Priya")
xw.WriteElementString("lname","Sharma")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code","3")
xw.WriteElementString("fname","Anshuman")
xw.WriteElementString("lname","Mohan")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code","4")
xw.WriteElementString("fname","Bibhuti")
xw.WriteElementString("lname","Banerjee")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code","5")
xw.WriteElementString("fname","Riyan")
xw.WriteElementString("lname","Sengupta")
xw.WriteEndElement()
xw.WriteEndElement()
xw.WriteEndDocument()
xw.Flush()
xw.Close()
WebBrowser1.Url=NewUri(AppDomain.CurrentDomain.BaseDirectory+"authors.xml")
EndSub
EndClass
ExecuteandruntheabovecodeusingStartbuttonavailableattheMicrosoftVisualStudio
toolbar.ClickingontheShowAuthorFilewoulddisplaythenewlycreatedauthors.xmlfileon
thewebbrowser.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 138/158
23/09/2016 VB.NetQuickGuide
ParsingXMLwithDOMAPI
According to the Document Object Model (DOM), an XML document consists of nodes and
attributesofthenodes.TheXmlDocumentclassisusedtoimplementtheXMLDOMparser
ofthe.NetFramework.ItalsoallowsyoutomodifyanexistingXMLdocumentbyinserting,
deletingorupdatingdatainthedocument.
FollowingaresomeofthecommonlyusedmethodsoftheXmlDocumentclass:
S.N MethodName&Description
1 AppendChild
Addsthespecifiednodetotheendofthelistofchildnodes,ofthisnode.
2 CreateAttribute(String)
CreatesanXmlAttributewiththespecifiedName.
3 CreateComment
CreatesanXmlCommentcontainingthespecifieddata.
4 CreateDefaultAttribute
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 139/158
23/09/2016 VB.NetQuickGuide
Createsadefaultattributewiththespecifiedprefix,localnameandnamespaceURI.
5 CreateElement(String)
Createsanelementwiththespecifiedname.
6 CreateNode(String,String,String)
CreatesanXmlNodewiththespecifiednodetype,Name,andNamespaceURI.
7 CreateNode(XmlNodeType,String,String)
CreatesanXmlNodewiththespecifiedXmlNodeType,Name,andNamespaceURI.
8 CreateNode(XmlNodeType,String,String,String)
9 CreateProcessingInstruction
CreatesanXmlProcessingInstructionwiththespecifiednameanddata.
10 CreateSignificantWhitespace
CreatesanXmlSignificantWhitespacenode.
11 CreateTextNode
CreatesanXmlTextwiththespecifiedtext.
12 CreateWhitespace
CreatesanXmlWhitespacenode.
13 CreateXmlDeclaration
CreatesanXmlDeclarationnodewiththespecifiedvalues.
14 GetElementById
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 140/158
23/09/2016 VB.NetQuickGuide
GetstheXmlElementwiththespecifiedID.
15 GetElementsByTagName(String)
ReturnsanXmlNodeListcontainingalistofalldescendantelementsthatmatchthe
specifiedName.
16 GetElementsByTagName(String,String)
ReturnsanXmlNodeListcontainingalistofalldescendantelementsthatmatchthe
specifiedLocalNameandNamespaceURI.
17 InsertAfter
Insertsthespecifiednodeimmediatelyafterthespecifiedreferencenode.
18 InsertBefore
Insertsthespecifiednodeimmediatelybeforethespecifiedreferencenode.
19 Load(Stream)
LoadstheXMLdocumentfromthespecifiedstream.
20 Load(String)
LoadstheXMLdocumentfromthespecifiedURL.
21 Load(TextReader)
LoadstheXMLdocumentfromthespecifiedTextReader.
22 Load(XmlReader)
LoadstheXMLdocumentfromthespecifiedXmlReader.
23 LoadXml
LoadstheXMLdocumentfromthespecifiedstring.
24
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 141/158
23/09/2016 VB.NetQuickGuide
PrependChild
Addsthespecifiednodetothebeginningofthelistofchildnodesforthisnode.
25 ReadNode
CreatesanXmlNodeobjectbasedontheinformationintheXmlReader.Thereader
mustbepositionedonanodeorattribute.
26 RemoveAll
Removesallthechildnodesand/orattributesofthecurrentnode.
27 RemoveChild
Removesspecifiedchildnode.
28 ReplaceChild
ReplacesthechildnodeoldChildwithnewChildnode.
29 Save(Stream)
SavestheXMLdocumenttothespecifiedstream.
30 Save(String)
SavestheXMLdocumenttothespecifiedfile.
31 Save(TextWriter)
SavestheXMLdocumenttothespecifiedTextWriter.
32 Save(XmlWriter)
SavestheXMLdocumenttothespecifiedXmlWriter.
Example3
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 142/158
23/09/2016 VB.NetQuickGuide
In this example, let us insert some new nodes in the xml document authors.xml and then
showalltheauthors'firstnamesinalistbox.
Takethefollowingsteps:
Add the authors.xml file in the bin/Debug folder of your application( it should be
thereifyouhavetriedthelastexample)
ImporttheSystem.Xmlnamespace
Addalistboxandabuttoncontrolintheformandsetthetextpropertyofthebutton
controltoShowAuthors.
Addthefollowingcodeusingthecodeeditor.
ImportsSystem.Xml
PublicClassForm1
PrivateSubForm1_Load(senderAsObject,eAsEventArgs)HandlesMyBase.Load
'Setthecaptionbartextoftheform.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click
ListBox1.Items.Clear()
DimxdAsXmlDocument=NewXmlDocument()
xd.Load("authors.xml")
DimnewAuthorAsXmlElement=xd.CreateElement("author")
newAuthor.SetAttribute("code","6")
DimfnAsXmlElement=xd.CreateElement("fname")
fn.InnerText="Bikram"
newAuthor.AppendChild(fn)
DimlnAsXmlElement=xd.CreateElement("lname")
ln.InnerText="Seth"
newAuthor.AppendChild(ln)
xd.DocumentElement.AppendChild(newAuthor)
DimtrAsXmlTextWriter=NewXmlTextWriter("movies.xml",Nothing)
tr.Formatting=Formatting.Indented
xd.WriteContentTo(tr)
tr.Close()
DimnlAsXmlNodeList=xd.GetElementsByTagName("fname")
ForEachnodeAsXmlNodeInnl
ListBox1.Items.Add(node.InnerText)
Nextnode
EndSub
EndClass
ExecuteandruntheabovecodeusingStartbuttonavailableattheMicrosoftVisualStudio
toolbar.ClickingontheShowAuthorbuttonwoulddisplaythefirstnamesofalltheauthors
includingtheonewehaveaddedatruntime.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 143/158
23/09/2016 VB.NetQuickGuide
VB.NetWebProgramming
Adynamicwebapplicationconsistsofeitherorbothofthefollowingtwotypesofprograms:
Clientsidescriptingtheseareprogramsexecutedonthebrowser,writtenusing
scriptinglanguageslikeJavaScript,VBScript,etc.
ASP.Netisthe.NetversionofASP,introducedbyMicrosoft,forcreatingdynamicwebpages
by using serverside scripts. ASP.Net applications are compiled codes written using the
extensibleandreusablecomponentsorobjectspresentin.Netframework.Thesecodescan
usetheentirehierarchyofclassesin.Netframework.
TheASP.Netapplicationcodescouldbewrittenineitherofthefollowinglanguages:
VisualBasic.Net
C#
Jscript
J#
In this chapter, we will give a very brief introduction to writing ASP.Net applications using
VB.Net.Fordetaileddiscussion,pleaseconsulttheASP.NetTutorial.
ASP.NetBuiltinObjects
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 144/158
23/09/2016 VB.NetQuickGuide
ASP.Net has some builtin objects that run on a web server. These objects have methods,
propertiesandcollectionsthatareusedinapplicationdevelopment.
ThefollowingtableliststheASP.Netbuiltinobjectswithabriefdescription:
Object Description
Application Describes the methods, properties, and collections of the object that
stores information related to the entire Web application, including
variablesandobjectsthatexistforthelifetimeoftheapplication.
Request Describes the methods, properties, and collections of the object that
stores information related to the HTTP request. This includes forms,
cookies,servervariables,andcertificatedata.
Youusethisobjecttoaccesstheinformationsentinarequestfroma
browser to the server. For example, you can use a Request object to
accessinformationenteredbyauserinanHTMLform.
Response Describes the methods, properties, and collections of the object that
stores information related to the server's response. This includes
displaying content, manipulating headers, setting locales, and
redirectingrequests.
You use this object to send information to the browser. For example,
you use a Response object to send output from your scripts to a
browser.
Server Describes the methods and properties of the object that provides
methodsforvariousservertasks.Withthesemethodsyoucanexecute
code, get error conditions, encode text strings, create objects for use
bytheWebpage,andmapphysicalpaths.
Youusethisobjecttoaccessvariousutilityfunctionsontheserver.For
example,youmayusetheServerobjecttosetatimeoutforascript.
Session
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 145/158
23/09/2016 VB.NetQuickGuide
You use this object to store and retrieve information about particular
user sessions. For example, you can use Session object to keep
information about the user and his preference and keep track of
pendingoperations.
ASP.NetProgrammingModel
ASP.Netprovidestwotypesofprogrammingmodels:
WebFormsthisenablesyoutocreatetheuserinterfaceandtheapplicationlogic
thatwouldbeappliedtovariouscomponentsoftheuserinterface.
WCFServicesthisenablesyoutoremoteaccesssomeserversidefunctionalities.
For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is
almostsameasyouhavealreadyusedforcreatingtheWindowsApplications.
WebForms
Webformsconsistsof:
Userinterface
Applicationlogic
UserinterfaceconsistsofstaticHTMLorXMLelementsandASP.Netservercontrols.When
youcreateawebapplication,HTMLorXMLelementsandservercontrolsarestoredinafile
with.aspxextension.Thisfileisalsocalledthepagefile.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 146/158
23/09/2016 VB.NetQuickGuide
Theapplicationlogicconsistsofcodeappliedtotheuserinterfaceelementsinthepage.You
writethiscodeinanyof.Netlanguagelike,VB.Net,orC#.
ThefollowingfigureshowsaWebForminDesignview:
Example
Let us create a new web site with a web form, which will show the current date and time,
whenauserclicksabutton.Takethefollowingsteps:
SelectFile>New>WebSite.TheNewWebSiteDialogBoxappears.
Select the ASP.Net Empty Web Site templates. Type a name for the web site and
selectalocationforsavingthefiles.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 147/158
23/09/2016 VB.NetQuickGuide
You need to add a Default page to the site. Right click the web site name in the
SolutionExplorerandselectAddNewItemoptionfromthecontextmenu.TheAdd
NewItemdialogboxisdisplayed:
SelectWebFormoptionandprovideanameforthedefaultpage.Wehavekeptitas
Default.aspx.ClicktheAddbutton.
TheDefaultpageisshowninSourceview
SetthetitlefortheDefaultwebpagebyaddingavaluetothe
Toaddcontrolsonthewebpage,gotothedesignview.Addthreelabels,atextbox
andabuttonontheform.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 148/158
23/09/2016 VB.NetQuickGuide
DoubleclickthebuttonandaddthefollowingcodetotheClickeventofthebutton:
ProtectedSubButton1_Click(senderAsObject,eAsEventArgs)_
HandlesButton1.Click
Label2.Visible=True
Label2.Text="WelcometoTutorialsPoint:"+TextBox1.Text
Label3.Text="Youvisitedusat:"+DateTime.Now.ToString()
EndSub
WhentheabovecodeisexecutedandrunusingStartbuttonavailableattheMicrosoftVisual
Studiotoolbar,thefollowingpageopensinthebrowser:
EnteryournameandclickontheSubmitbutton:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 149/158
23/09/2016 VB.NetQuickGuide
WebServices
Awebserviceisawebapplication,whichisbasicallyaclassconsistingofmethodsthatcould
beusedbyotherapplications.ItalsofollowsacodebehindarchitectureliketheASP.Netweb
pages,althoughitdoesnothaveanuserinterface.
Thepreviousversionsof.NetFrameworkusedthisconceptofASP.NetWebService,which
had .asmx file extension. However, from .Net Framework 4.0 onwards, the Windows
Communication Foundation (WCF) technology has evolved as the new successor of Web
Services,.NetRemotingandsomeotherrelatedtechnologies.Ithasratherclubbedallthese
technologies together. In the next section, we will provide a brief introduction to Windows
CommunicationFoundation(WCF).
If you are using previous versions of .Net Framework, you can still create traditional web
services.PleaseconsultASP.NetWebServices tutorialfordetaileddescription.
WindowsCommunicationFoundation
WindowsCommunicationFoundationorWCFprovidesanAPIforcreatingdistributedservice
orientedapplications,knownasWCFServices.
LikeWebservices,WCFservicesalsoenablecommunicationbetweenapplications.However,
unlike web services, the communication here is not limited to HTTP only. WCF can be
configured to be used over HTTP, TCP, IPC, and Message Queues. Another strong point in
favourofWCFis,itprovidessupportforduplexcommunication,whereaswithwebservices
wecouldachievesimplexcommunicationonly.
From beginners' point of view, writing a WCF service is not altogether so different from
writingaWebService.Tokeepthethingssimple,wewillseehowto:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 150/158
23/09/2016 VB.NetQuickGuide
CreateaWCFService
CreateaServiceContractanddefinetheoperations
Implementthecontract
TesttheService
UtilizetheService
Example
To understand the concept let us create a simplistic service that will provide stock price
information.Theclientscanqueryaboutthenameandpriceofastockbasedonthestock
symbol.Tokeepthisexamplesimple,thevaluesarehardcodedinatwodimensionalarray.
Thisservicewillhavetwomethods:
GetPriceMethoditwillreturnthepriceofastock,basedonthesymbolprovided.
GetName Method it will return the name of the stock, based on the symbol
provided.
CreatingaWCFService
Takethefollowingsteps:
OpenVSExpressforWeb2012
SelectNewWebSitetoopentheNewWebSitedialogbox.
SelectWCFServicetemplatefromlistoftemplates:
SelectFileSystemfromtheWeblocationdropdownlist.
ProvideanameandlocationfortheWCFServiceandclickOK.
AnewWCFServiceiscreated.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 151/158
23/09/2016 VB.NetQuickGuide
CreatingaServiceContractandDefiningtheOperations
A service contract defines the operation that a service performs. In the WCF Service
application, you will find two files automatically created in the App_Code folder in the
SolutionExplorer
IService.vb this will have the service contract in simpler words, it will have the
interface for the service, with the definitions of methods the service will provide,
whichyouwillimplementinyourservice.
Service.vbthiswillimplementtheservicecontract.
ReplacethecodeoftheIService.vbfilewiththegivencode:
PublicInterfaceIService
<OperationContract()>
FunctionGetPrice(ByValsymbolAsString)AsDouble
<OperationContract()>
FunctionGetName(ByValsymbolAsString)AsString
EndInterface
ImplementingtheContract
IntheService.vbfile,youwillfindaclassnamedServicewhichwillimplementtheService
ContractdefinedintheIServiceinterface.
ReplacethecodeofIService.vbwiththefollowingcode:
'NOTE:Youcanusethe"Rename"commandonthecontextmenutochangetheclassname"Service"incode,s
PublicClassService
ImplementsIService
PublicSubNew()
EndSub
DimstocksAsString(,)=
{
{"RELIND","RelianceIndustries","1060.15"},
{"ICICI","ICICIBank","911.55"},
{"JSW","JSWSteel","1201.25"},
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 152/158
23/09/2016 VB.NetQuickGuide
{"WIPRO","WiproLimited","1194.65"},
{"SATYAM","SatyamComputers","91.10"}
}
PublicFunctionGetPrice(ByValsymbolAsString)AsDouble_
ImplementsIService.GetPrice
DimiAsInteger
'ittakesthesymbolasparameterandreturnsprice
Fori=0Toi=stocks.GetLength(0)1
If(String.Compare(symbol,stocks(i,0))=0)Then
ReturnConvert.ToDouble(stocks(i,2))
EndIf
Nexti
Return0
EndFunction
PublicFunctionGetName(ByValsymbolAsString)AsString_
ImplementsIService.GetName
'Ittakesthesymbolasparameterand
'returnsnameofthestock
DimiAsInteger
Fori=0Toi=stocks.GetLength(0)1
If(String.Compare(symbol,stocks(i,0))=0)Then
Returnstocks(i,1)
EndIf
Nexti
Return"StockNotFound"
EndFunction
EndClass
TestingtheService
To run the WCF Service, so created, select the Debug>Start Debugging option from the
menubar.Theoutputwouldbe:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 153/158
23/09/2016 VB.NetQuickGuide
Fortestingtheserviceoperations,doubleclickthenameoftheoperationfromthetreeon
theleftpane.Anewtabwillappearontherightpane.
Enter the value of parameters in the Request area of the right pane and click the 'Invoke'
button.
ThefollowingdiagramdisplaystheresultoftestingtheGetPriceoperation:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 154/158
23/09/2016 VB.NetQuickGuide
ThefollowingdiagramdisplaystheresultoftestingtheGetNameoperation:
UtilizingtheService
Letusaddadefaultpage,aASP.NETwebforminthesamesolutionfromwhichwewillbe
usingtheWCFServicewehavejustcreated.
Takethefollowingsteps:
RightclickonthesolutionnameintheSolutionExplorerandaddanewwebformto
thesolution.ItwillbenamedDefault.aspx.
Addtwolabels,atextboxandabuttonontheform.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 155/158
23/09/2016 VB.NetQuickGuide
WeneedtoaddaservicereferencetotheWCFservicewejustcreated.Rightclick
the website in the Solution Explorer and select Add Service Reference option. This
openstheAddServiceReferenceDialogbox.
Enter the URL(location) of the Service in the Address text box and click the Go
button. It creates a service reference with the default name ServiceReference1.
ClicktheOKbutton.
Addingthereferencedoestwojobsforyourproject:
CreatestheAddressandBindingfortheserviceintheweb.configfile.
Createsaproxyclasstoaccesstheservice.
DoubleclicktheGetPricebuttonintheform,toenterthefollowingcodesnippeton
itsClickevent:
PartialClass_Default
InheritsSystem.Web.UI.Page
ProtectedSubButton1_Click(senderAsObject,eAsEventArgs)_
HandlesButton1.Click
DimserAsServiceReference1.ServiceClient=_
NewServiceReference1.ServiceClient
Label2.Text=ser.GetPrice(TextBox1.Text).ToString()
EndSub
EndClass
WhentheabovecodeisexecutedandrunusingStartbuttonavailableattheMicrosoftVisual
Studiotoolbar,thefollowingpageopensinthebrowser:
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 156/158
23/09/2016 VB.NetQuickGuide
EnterasymbolandclicktheGetPricebuttontogetthehardcodedprice:
PreviousPage NextPage
Advertisements
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 157/158
23/09/2016 VB.NetQuickGuide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 158/158