SlideShare a Scribd company logo
1 of 80
UNIT 1
Introduction to Visual Basic programming
Unit Covered
 Introduction to visual studio
 Variables:
 Data type conversions, operators and its precedence,
boxing and un-boxing
 Flow control in VB
 Procedures: subroutines and functions.
 Array.
 Strings, StringBuilder and Enumerations
 Exception handling in VB.NET
IDE
 Stands for Integrated Development Environment
 Visual Studio is a powerful and customizable
programming environment that contains all the tools
you need to build programs quickly and efficiently.
 It offers a set of tools that help you
– To write and modify the code for your programs
– Detect and correct errors in your programs.
3
IDE cont…
It includes
1. Menu Bar
2. Standard Toolbar
3. Toolbox
4. Forms Designer
5. Output Window
6. Solution Explorer
7. Properties Window
8. Server Explorer 4
5
What is DataType?
 In a programming language describes that what type of
data a variable can hold .
 When we declare a variable, we have to tell the
compiler about what type of the data the variable can
hold or which data type the variable belongs to.
What is Variable?
 Variables are used to store data.
 Symbolic names given to values stored in memory and
declared with the Dim keyword
 Dim stands for Dimension.
 constants
– The same as variables, except that constants are
assigned a value that cannot then be altered.
How to declare Variable?
 Syntax :
Dim VariableName as DataType
VariableName : the variable we declare for hold the
values.
DataType : The type of data that the variable can
hold
 Example :
Dim count as Integer
count : is the variable name
Integer : is the data type
List of Data types
Type Storage size Value range
Boolean 2 bytes True or False
Byte 1 byte 0 to 255 (unsigned)
Char 2 bytes 0 to 65535 (unsigned)
Date 8 bytes January 1, 0001 to December 31, 9999
Decimal 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with no
decimal point;
Double 8 bytes -1.79769313486231E+308 to -4.94065645841247E-
324 for negative values;
4.94065645841247E-324 to .79769313486231E+308
for positive values
Integer 4 bytes -2,147,483,648 to 2,147,483,647
List of Data types
Type Storage
size
Value range
Long 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Object 4 bytes Any type can be stored in a variable of type
Object
Short 2 bytes -32,768 to 32,767
Single 4 bytes -3.402823E to -1.401298E-45 for negative
values; 1.401298E-45 to 3.402823E for
positive values
String Depends on
platform
0 to approximately 2 billion Unicode
characters
User-Defined
Type
(structure)
Sum of the sizes of its members. Each member of the
structure has a range determined by its data type and
independent of the ranges of the other members
Access Specifiers
 Public: Gives variable public access which means that
there is no restriction on their accessibility
 Private: Gives variable private access which means that
they are accessible only within their declaration content
 Protected: Protected access gives a variable
accessibility within their own class or a class derived
from that class
 Friend: Gives variable friend access which means that
they are accessible within the program that contains
their declaration
Access Specifiers
 Protected Friend: Gives a variable both protected and
friend access
 Static: Makes a variable static which means that the
variable will hold the value even the procedure in
which they are declared ends
 Shared: Declares a variable that can be shared across
many instances and which is not associated with a
specific instance of a class or structure
 ReadOnly: Makes a variable only to be read and cannot
be written
Scope of Variable
 Scope : Element's scope is its accessibility in your code.
 Block scope —available only within the code block in which it is
declared
 Procedure scope —available only within the procedure in
which it is declared
 Module scope —available to all code within the module, class,
or structure in which it is declared
 Namespace scope —available to all code in the namespace
Option Statement
 The Option statement is used to set a number of
options for the code to prevent syntax and
logical errors.
 This statement is normally the first line of the code.
 The Option values in Visual Basic are as follows.
– Option Explicit
– Option Strict
– Option Compare
Option Explicit
 Option Explicit
– Set to On or Off
– Default : On
– This requires to declare all the variables before they
are used.
Option Explicit
 If Option Explicit mode in ON ,
– have to declare all the variable before you use it in
the program .
 If the Option Explicit mode is OFF
– VB.Net automatically create a variable whenever it
sees a variable without proper declaration.
 CODE
Option Strict
 Option Strict
– Set to On or Off.
– Default : off
– Used normally when working with conversions in
code.
– Option Strict is prevents program from automatic
variable conversions, that is implicit data type
conversions .
Option Strict
– If Option is on and you assign a value of one type to
a variable of another type Visual Basic will consider
error.
– There is any possibility of data loss, as when you're
trying to assign the value in a variable to a variable
of less precise data storage capacity.
– In that case, you must use explicit conversion.
 CODE
Option Compare
 Default : Binary.
 Binary - Optional - compares based on binary
representation - case sensitive
 Text - Optional - compares based on text
representation - case insensitive
 Code
Type Conversion
 In Visual Basic, data can be converted in two
ways:
– Implicitly (widening), which means the conversion
is performed automatically,
– Explicitly(narrowing), which means you must
perform the conversion.
 Implicit Conversions (widening Conversion)
 Widening conversion is one where the new data is
always big enough to hold the old datatype’s value.
 For example
– Long is big enough to hold any integer.
– Copying an integer value in to long variable is widening
conversion.
Example
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=5
i=d
d=i
Console.WriteLine("Integer value is" & i)
End Sub
End Module
Explicit Conversions (Narrowing Conversion)
– When types cannot be implicitly converted you
should convert them explicitly.
– This conversion is also called as cast.
– Explicit conversions are accomplished using CType
function.
i = CType(d, Integer)
or
i=CInt(d)
Code
Example
Module Module1
Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, Integer)
'two arguments, type we are converting
'from, to type desired
Console.WriteLine("Integer value is " & i)
Console.ReadKey()
End Sub
End Module
CType
Below is the list of conversion functions which we can use in VB .NET.
 CBool— Convert to Bool data type.
 CByte— Convert to Byte data type.
 CChar— Convert to Char data type.
 CDate— Convert to Date data type.
 CDbl— Convert to Double data type.
 CDec— Convert to Decimal data type.
 CInt— Convert to Int data type.
 CLng— Convert to Long data type.
 CObj— Convert to Object type.
 CShort— Convert to Short data type.
 CSng— Convert to Single data type.
 CStr— Convert to String type.
Operators
An operator is a symbol used to perform
operation on one or more operands.
Syntax
Oper1=oper2 operator oper3
Example
Sum=a+b
Operators
Arithmetic Operators
Operator Use
^ Exponentiation
-
Negation (used to reverse the sign
of the given value, exp -intValue)
* Multiplication
/ Division
 Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Operators
Concatenation Operators
Operator Use
+ String Concatenation
& String Concatenation
Difference
Preview
/ operator  operator
It is used for Division It is used for Integer Division
e.g.
Dim a As Integer
a = 19 / 5
Result : 4
e.g.
Dim a As Integer
a = 19  5
Result : 3
Operators
Comparison Operators
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
Operators
Logical / Bitwise Operators
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
Operator Precedence
1. Arithmetic operators have the highest precedence and
are arranged this way, from highest precedence to
lowest:
– Exponentiation (^)
– Negation (-) (for example, -intValue reverses the sign of the
value in intValue)
– Multiplication and division (*, /)
– Integer division ()
– Modulus arithmetic (Mod)
– Addition and subtraction (+,-)
2. Concatenation operators:
– String concatenation (+)
– String concatenation (&)
Operator Precedence
3. Comparison operators, which all have the same
precedence and are evaluated from left to right
– Equality (=)
– Inequality (<>)
– Less than, greater than (<,>)
– Greater than or equal to (>=)
– Less than or equal to (<=)
4. Logical/Bitwise operators, which have this
precedence order, from highest to lowest:
– Negation-(Not)
– Conjunction-(And,AndAlso)
– Disjunction-(Or, OrElse, Xor)
Flow control in VB:
 Conditional Statement
 Selection statement
 Iteration statement
 jump statement
Conditional Statements
 If....Else statement
 Syntax
If condition Then
[statements]
Else If condition Then
[statements]
-
-
Else
[statements]
End If
Example
Module Module1
Sub Main()
Dim a,b As Integer
If a=b Then
Console.WriteLine(“a equal to b”)
ElseIf a<b Then
Console.WriteLine(“a less than b")
Else
Console.WriteLine(" a greater than b")
End If
Console.ReadKey()
End Sub
End Module
Select....Case Statement
 It is used to avoid long chains of If….Then….ElseIf
statement.
 It compare one specific variable against several
constant expressions then we use select….case
statement.
Select Statements
 The syntax of the Select Case statement
Select Case test_expression
Case expressionlist-1
statements-1
Case expressionlist-n
statements-n. . .
Case Else
else_statements
End Select
Example
Module Module1
Sub Main()
Dim i As Integer
Console.WriteLine("Enter a number between 1 and 4")
i = Val(Console.ReadLine())
Select Case i
Case 1
Console.WriteLine("You entered 1")
Case 2
Console.WriteLine("You entered 2")
Case Else
Console.WriteLine("You entered >2")
End Select
Console.ReadKey()
End Sub
End Module
Iteration Statement
For Loop
 The For loop in VB .NET needs a loop index which counts
the number of loop iterations as the loop executes.
 The syntax for the For loop looks like this:
For index=start to end [Step stepvalue]
[statements]
Next[index]
Example
Module Module1
Sub Main()
Dim d As Integer
For d = 0 To 2
Console.WriteLine("In the For Loop")
Next d
End Sub
End Module
While loop
 It runs set of statements as long as the conditions
specified with while loop is true.
 The syntax of while loop looks like this:
While condition
[statements]
End While
Example
Module Module1 OUTPUT
Sub Main()
Dim d, e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
Console.WriteLine("The Loop run " & e & "times")
End Sub
End Module
Do Loop
Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
 The Do loop can be used to execute a fixed block of
statements indefinite number of times.
 The Do loop keeps executing it's statements while or
until the condition is true.
 The syntax of Do loop looks like this:
Do
[statements]
[Exit Do]
[statements]
Loop [{while | Until} condition]
Example
Module Module1 Output
Sub Main()
Dim str As String
Console.WriteLine("What to do?")
str = Console.ReadLine()
Do Until str = "Cool"
Console.WriteLine("What to do?")
str = Console.ReadLine()
Loop
Console.ReadKey()
End Sub
End Module
Example
 Write a console application to find out n!.(use for loop)
 Write a console application to find out sum of the digits.
– i.e. 1237 : 1+2+3+7 = 13.(using while condition)
 Write a program to enter marks of student and
calculate grade of the student.
Procedure
 They are a series of statements that are executed when
called.
 There are two types of procedure in VB .NET:
– Function : Those that return a value.
– Subroutines (Procedure) : Those that do not return
a value.
Sub Procedure
 Sub procedures are methods which do not return a value.
 Each time when the Sub procedure is called the
statements within it are executed until the matching End
Sub is encountered.
 Sub Main(), the starting point of the program itself is a
sub procedure.
 Sub routine can be created in module and class.
 Default access modifier is public.
Syntax
[{ Overloads | Overrides | Overridable | NotOverridable |
MustOverride | Shadows | Shared }]
[Access_Specifiers] Sub ProcedureName[(argument list)]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub
Code
 Access_Specifiers : Public | Protected | Friend |
Protected Friend | Private
 Attribute List - List of attributes for this procedure. You
separate multiple attributes with commas.
– ByVal : Pass by value
– ByRef : Pass by Reference.
 Procedure Name: Name of the Procedure
 Exit Sub : Explicitly exit a sub procedure.
 Overloads : it indicates that there are other procedure in the class
with the same name but with different argument.
 Overrides :-Specifies that this Sub procedure overrides a procedure
with the same name in a base class.
 Overridable : -Specifies that this Sub procedure can be overridden
by a procedure with the same name in a derived class.
 NotOverridable:- Specifies that this Sub procedure may not be
overridden in a derived class.
 MustOverride:-Specifies that this Sub procedure is not
implemented in class and must be implemented in a derived class.
Function
 Function is a method which returns a value.
 Functions are used to evaluate data, make calculations
or to transform data.
 Functions are declared with the Function keyword.
Syntax
[{ Overloads | Overrides | Overridable | NotOverridable |
MustOverride | Shadows | Shared }]
[Access_Specifiers] Function Func_name[argument List ]
[ As type ]
[ statements ]
[ Exit Function ]
[statements ]
End Function
 Type- Data type of the value returned by the Function
procedure can be
– Boolean, Byte, Char, Date, Decimal, Double, Integer,
Long, Object, Short, Single, or String;
 Access_Specifiers : Public | Protected | Friend |
Protected Friend | Private
 Code
Example
 The calculate_Amount sub routine takes the quantity
and unit price of product and calculate the total
amount.
 The calculate_Amount sub routine takes the quantity
and unit price of product and return total amount.
Array
 It is a collection of elements of same datatype.
 It access using single name and index number.
 This is very useful when you are working on several
pieces of data that all have the same variable datatype &
purpose.
Type of Array Demo
 One dimensional
Dim Array_name(size) as Datatype
e. g. Dim name(20) As String
Dim Array_name() as Datatype=new data type(size){list of
constant separated by comma}
e.g. Dim num() as integer=New integer(5) {1,2,3,4,5}
 Multidimensional
e. g. Dim matrix(3,3) As Integer
Dim mat(,) as Integer=New Integer(3,3)
Dim matrix(,) As Integer =New Integer(){{2,2},{0,0},{1,3}}
Dynamic Array
 You can resize an array using ReDim Keyword.
 Syntax
ReDim [Preserve] Array_name(new Size)
 If you use ReDim statement then existing content are
erased.
 If you want to preserve existing data when reinitializing
an array then you should use the Preserve keyword .
Dim Test() as Integer={1,3,5}
'declares an array an initializes it with three members
ReDim Test(25)
'resizes the array and lost existing data.
ReDim Preserve Test(25)
'resizes the array and retains the data in elements 0 to 2
Demo
Function In Array
Function Description
GetLength Get length of the array
GetType Get Datatype of an array
First It gets the first element of an array.
Last It gets the last element of an array.
Max It gets the Maximum element of an array.
Min It gets the Minimum element of an array.
For Each……Next Loop
This element automatically loops over all the element
in array or collection.
No need to write starting or ending index.
Syntax
For Each element in group
[statement]
[Exit For]
[Statement]
Next [Element]
Example
Difference
For For Each
The for loop executes a statement or
a block of statements repeatedly until
a specified expression evaluates to
false.
The for Each statement repeats a
group of embedded statements for
each element in an array or an object
collection.
Need to specify the loop bounds No not need to specify the loop
bounds minimum or maximum
Syntax :
For index=start to end [Step]
[statements]
[statements]
Next[index]
Syntax :
For Each element in group
[statement]
[Exit For]
[Statement]
Next [Element]
Difference
While Until
"do while" loops while the test case is
true.
“do until ” loops while the test case is
false.
Syntax :
Do while condition
[statements]
[Exit Do]
[statements]
Loop
Syntax :
Do Until condition
[statements]
[Exit Do]
[statements]
Loop
String Function Code
To Do This To USE
Concatenate two strings &, +, String.Concat, String.Join
Compare two strings
StrComp Return Zero if same else 1
String.Compare Return zero if same else 1
String.Equals Return true if same else false
String.CompareTo Return Zero if same else false
Convert strings CStr, String. ToString
Copying strings =, String.Copy
Convert to lowercase or
uppercase
Lcase, Ucase,
String. ToUpper, String. ToLower
String Function
To Do This To USE
Create an array of strings from
one string
String.Split
Find length of a string Len, String.Length
Get a substring Mid, String.SubString
Insert a substring String.Insert
Remove text String.Remove
Replace text String.Replace
String Function
To Do This To USE
Search strings InStr, String.Chars,
String.IndexOf,
String.LastIndexOf,
Trim leading or trailing spaces
(Remove Unwanted space)
LTrim, RTrim, Trim,
String.Trim,
String.TrimEnd,
String.TrimStart
Work with character codes Asc, Chr
Enumeration
Access Modifier : (Optional) Public, Protected, Friend,
Private
[ access modifier ]
Enum enumeration_name [ As data type ]
member list
End Enum
Example
Enum Days Demo
Monday=1
Tuesday=2
Wednesday=3
Thursday=4
Friday=5
Saturday=6
Sunday=7
End Enum
Sub Main()
Console.WriteLine(“Friday is a day” & Days.Friday)
End Sub
Exception
 Exceptions : It is a runtime errors that occur when a
program is running and causes the program to abort
without execution.
 Such kind of situations can be handled using Exception
Handling.
 Exception Handling :
– By placing specific lines of code in the application we
can handle most of the errors that we may encounter
and we can enable the application to continue running.
 VB .NET supports two ways to handle exceptions,
– Unstructured exception Handling
– using the On Error goto statement
– Structured exception handling
– using Try....Catch.....Finally

Unstructured Exception Handling
 The On Error GoTo statement enables exception
handling and specifies the location of the exception-
handling code within a procedure.
 How the On Error GoTo statement works:
On Error GoTo [ lable | 0 | -1 ] | Resume Next
Code
Statement Meaning
On Error GoTo -1 Resets Err object to Nothing, disabling error
handling in the routine
On Error GoTo 0 Resets last exception-handler location to
Nothing, disabling the exception.
On Error GoTo
<labelname>
Sets the specified label as the location of the
exception handler
On Error Resume
Next
Specifies that when an exception occurs,
execution skips over the statement that caused
the problem and goes to the statement
immediately following. Execution continues
from that point.
Structured Exception Handling
 On Error Goto method of exception handling sets the
internal exception handler in Visual Basic.
 It certainly doesn't add any structure to your code,
 If your code extends over procedures and blocks, it can
be hard to figure out what exception handler is working
when.
 Structured exception handling is based on a particular
statement, the Try…Catch…Finally statement, which is
divided into a
– Try block,
– optional Catch blocks,
– and an optional Finally block.
Syntax
Try
//code where exception occurs
Catch e as Exception
// handle exception
Finally
// final Statement
End Try
 The Try block contains code where exceptions can
occur.
 The Catch block contains code to handle the exceptions
that occur.
 If an exception occurs in the Try block, the code throws
the exception.
 It can be caught and handled by the appropriate Catch
statement.
 After the rest of the statement finishes, execution is
always passed to the Finally block, if there is one.
Code
Exception Object
 The Exception object provides information about any
encountered exception.
 properties of the Exception object:
– HelpLink : can hold an URL that points the user to
further information about the exception.
– InnerException : It returns an exception object
representing an exception that was already in the
process of being handled when the current
exception was thrown.
– Message : It holds a string, which is the text
message that informs the user of the nature of the
error and the best way or ways to address it.
– StackTrace : It holds a stack trace, which you can
use to determine where in the code the error
occurred.
Standard Exception
Exception Type Description
Exception Base type for all exceptions
IndexOutOfRangeException Thrown when you try to access an array
index improperly
NullReferenceException Thrown when you try to access a null
reference
InvalidOperationException Thrown when a class is in an invalid
state
ArgumentException Thrown when you pass an invalid
argument to a method
ArithmeticException Thrown for general arithmetic errors
Difference
VALUE TYPE REFERENCE TYPE
Value type they are stored on
stack
Reference type they are stored on heap
When passed as value type new
copy is created and passed so
changes to variable does not get
reflected back
When passed as Reference type then
reference of that variable is passed so
changes to variable does get reflected
back
Value type store real data
Reference type store reference to the
data.
Value type consists of primitive
data types, structures,
enumerations.
Reference type consists of class, array,
interface, delegates
Value types derive from
System.ValueType
Reference types derive from
System.Object

More Related Content

What's hot (20)

MySQL ppt
MySQL ppt MySQL ppt
MySQL ppt
 
Decision Table Based Testing
Decision Table Based TestingDecision Table Based Testing
Decision Table Based Testing
 
Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
 
0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
 
Chapter 1 introduction
Chapter 1 introductionChapter 1 introduction
Chapter 1 introduction
 
Software design
Software designSoftware design
Software design
 
Temporal databases
Temporal databasesTemporal databases
Temporal databases
 
Cause effect graphing.ppt
Cause effect graphing.pptCause effect graphing.ppt
Cause effect graphing.ppt
 
COCOMO Model
COCOMO ModelCOCOMO Model
COCOMO Model
 
page replacement.pptx
page replacement.pptxpage replacement.pptx
page replacement.pptx
 
Requirement analysis and specification
Requirement analysis and specificationRequirement analysis and specification
Requirement analysis and specification
 
File Organization
File OrganizationFile Organization
File Organization
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Daa notes 1
Daa notes 1Daa notes 1
Daa notes 1
 
Ai lecture 01(unit03)
Ai lecture  01(unit03)Ai lecture  01(unit03)
Ai lecture 01(unit03)
 
Net framework
Net frameworkNet framework
Net framework
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
Design Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptxDesign Concepts in Software Engineering-1.pptx
Design Concepts in Software Engineering-1.pptx
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.net
 

Viewers also liked

chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)It Academy
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programmingChitrank Dixit
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constantsvinay arora
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in CSahithi Naraparaju
 
Transforming the world with Information technology
Transforming the world with Information technologyTransforming the world with Information technology
Transforming the world with Information technologyGlenn Klith Andersen
 
Pioneers of Information Science in Europe: The Oeuvre of Norbert Henrichs
Pioneers of Information Science in Europe: The Oeuvre of Norbert HenrichsPioneers of Information Science in Europe: The Oeuvre of Norbert Henrichs
Pioneers of Information Science in Europe: The Oeuvre of Norbert HenrichsWolfgang Stock
 
Part 1 picturebox using vb.net
Part 1 picturebox using vb.netPart 1 picturebox using vb.net
Part 1 picturebox using vb.netGirija Muscut
 
Vb.net session 15
Vb.net session 15Vb.net session 15
Vb.net session 15Niit Care
 
How Not To Be Seen
How Not To Be SeenHow Not To Be Seen
How Not To Be SeenMark Pesce
 
What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++Microsoft
 
Part 5 create sequence increment value using negative value
Part 5 create sequence increment value using negative valuePart 5 create sequence increment value using negative value
Part 5 create sequence increment value using negative valueGirija Muscut
 
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uPython Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uNikola Plejic
 

Viewers also liked (20)

chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)chap4 : Converting and Casting (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)
 
Chapter 07
Chapter 07 Chapter 07
Chapter 07
 
Array ppt
Array pptArray ppt
Array ppt
 
Programming Variables
Programming VariablesProgramming Variables
Programming Variables
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
 
Chapter1 c programming data types, variables and constants
Chapter1 c programming   data types, variables and constantsChapter1 c programming   data types, variables and constants
Chapter1 c programming data types, variables and constants
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Data type
Data typeData type
Data type
 
Transforming the world with Information technology
Transforming the world with Information technologyTransforming the world with Information technology
Transforming the world with Information technology
 
Pioneers of Information Science in Europe: The Oeuvre of Norbert Henrichs
Pioneers of Information Science in Europe: The Oeuvre of Norbert HenrichsPioneers of Information Science in Europe: The Oeuvre of Norbert Henrichs
Pioneers of Information Science in Europe: The Oeuvre of Norbert Henrichs
 
Information Overload and Information Science / Mieczysław Muraszkiewicz
Information Overload and Information Science / Mieczysław MuraszkiewiczInformation Overload and Information Science / Mieczysław Muraszkiewicz
Information Overload and Information Science / Mieczysław Muraszkiewicz
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Part 1 picturebox using vb.net
Part 1 picturebox using vb.netPart 1 picturebox using vb.net
Part 1 picturebox using vb.net
 
Vb.net session 15
Vb.net session 15Vb.net session 15
Vb.net session 15
 
How Not To Be Seen
How Not To Be SeenHow Not To Be Seen
How Not To Be Seen
 
What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++What&rsquo;s new in Visual C++
What&rsquo;s new in Visual C++
 
Part 5 create sequence increment value using negative value
Part 5 create sequence increment value using negative valuePart 5 create sequence increment value using negative value
Part 5 create sequence increment value using negative value
 
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-uPython Tools for Visual Studio: Python na Microsoftovom .NET-u
Python Tools for Visual Studio: Python na Microsoftovom .NET-u
 
Presentation1
Presentation1Presentation1
Presentation1
 

Similar to Unit 1 introduction to visual basic programming

Similar to Unit 1 introduction to visual basic programming (20)

E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Introduction to Visual Basic
Introduction to Visual Basic Introduction to Visual Basic
Introduction to Visual Basic
 
I x scripting
I x scriptingI x scripting
I x scripting
 
UNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCAUNIT-II VISUAL BASIC.NET | BCA
UNIT-II VISUAL BASIC.NET | BCA
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
C#
C#C#
C#
 
C material
C materialC material
C material
 
Pc module1
Pc module1Pc module1
Pc module1
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Visual Basics for Application
Visual Basics for Application Visual Basics for Application
Visual Basics for Application
 
C++ data types
C++ data typesC++ data types
C++ data types
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12
 

More from Abha Damani (20)

Unit2
Unit2Unit2
Unit2
 
Unit6
Unit6Unit6
Unit6
 
Unit5
Unit5Unit5
Unit5
 
Unit4
Unit4Unit4
Unit4
 
Unit3
Unit3Unit3
Unit3
 
Ch14
Ch14Ch14
Ch14
 
Ch12
Ch12Ch12
Ch12
 
Ch11
Ch11Ch11
Ch11
 
Ch10
Ch10Ch10
Ch10
 
Ch08
Ch08Ch08
Ch08
 
Ch01 enterprise
Ch01 enterpriseCh01 enterprise
Ch01 enterprise
 
3 data mgmt
3 data mgmt3 data mgmt
3 data mgmt
 
2 it supp_sys
2 it supp_sys2 it supp_sys
2 it supp_sys
 
1 org.perf it supp_appl
1 org.perf it supp_appl1 org.perf it supp_appl
1 org.perf it supp_appl
 
Managing and securing the enterprise
Managing and securing the enterpriseManaging and securing the enterprise
Managing and securing the enterprise
 
Ch6
Ch6Ch6
Ch6
 
Unit2
Unit2Unit2
Unit2
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 5
Unit 5Unit 5
Unit 5
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Unit 1 introduction to visual basic programming

  • 1. UNIT 1 Introduction to Visual Basic programming
  • 2. Unit Covered  Introduction to visual studio  Variables:  Data type conversions, operators and its precedence, boxing and un-boxing  Flow control in VB  Procedures: subroutines and functions.  Array.  Strings, StringBuilder and Enumerations  Exception handling in VB.NET
  • 3. IDE  Stands for Integrated Development Environment  Visual Studio is a powerful and customizable programming environment that contains all the tools you need to build programs quickly and efficiently.  It offers a set of tools that help you – To write and modify the code for your programs – Detect and correct errors in your programs. 3
  • 4. IDE cont… It includes 1. Menu Bar 2. Standard Toolbar 3. Toolbox 4. Forms Designer 5. Output Window 6. Solution Explorer 7. Properties Window 8. Server Explorer 4
  • 5. 5
  • 6. What is DataType?  In a programming language describes that what type of data a variable can hold .  When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to.
  • 7. What is Variable?  Variables are used to store data.  Symbolic names given to values stored in memory and declared with the Dim keyword  Dim stands for Dimension.  constants – The same as variables, except that constants are assigned a value that cannot then be altered.
  • 8. How to declare Variable?  Syntax : Dim VariableName as DataType VariableName : the variable we declare for hold the values. DataType : The type of data that the variable can hold  Example : Dim count as Integer count : is the variable name Integer : is the data type
  • 9. List of Data types Type Storage size Value range Boolean 2 bytes True or False Byte 1 byte 0 to 255 (unsigned) Char 2 bytes 0 to 65535 (unsigned) Date 8 bytes January 1, 0001 to December 31, 9999 Decimal 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; Double 8 bytes -1.79769313486231E+308 to -4.94065645841247E- 324 for negative values; 4.94065645841247E-324 to .79769313486231E+308 for positive values Integer 4 bytes -2,147,483,648 to 2,147,483,647
  • 10. List of Data types Type Storage size Value range Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Object 4 bytes Any type can be stored in a variable of type Object Short 2 bytes -32,768 to 32,767 Single 4 bytes -3.402823E to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E for positive values String Depends on platform 0 to approximately 2 billion Unicode characters User-Defined Type (structure) Sum of the sizes of its members. Each member of the structure has a range determined by its data type and independent of the ranges of the other members
  • 11. Access Specifiers  Public: Gives variable public access which means that there is no restriction on their accessibility  Private: Gives variable private access which means that they are accessible only within their declaration content  Protected: Protected access gives a variable accessibility within their own class or a class derived from that class  Friend: Gives variable friend access which means that they are accessible within the program that contains their declaration
  • 12. Access Specifiers  Protected Friend: Gives a variable both protected and friend access  Static: Makes a variable static which means that the variable will hold the value even the procedure in which they are declared ends  Shared: Declares a variable that can be shared across many instances and which is not associated with a specific instance of a class or structure  ReadOnly: Makes a variable only to be read and cannot be written
  • 13. Scope of Variable  Scope : Element's scope is its accessibility in your code.  Block scope —available only within the code block in which it is declared  Procedure scope —available only within the procedure in which it is declared  Module scope —available to all code within the module, class, or structure in which it is declared  Namespace scope —available to all code in the namespace
  • 14. Option Statement  The Option statement is used to set a number of options for the code to prevent syntax and logical errors.  This statement is normally the first line of the code.  The Option values in Visual Basic are as follows. – Option Explicit – Option Strict – Option Compare
  • 15. Option Explicit  Option Explicit – Set to On or Off – Default : On – This requires to declare all the variables before they are used.
  • 16. Option Explicit  If Option Explicit mode in ON , – have to declare all the variable before you use it in the program .  If the Option Explicit mode is OFF – VB.Net automatically create a variable whenever it sees a variable without proper declaration.  CODE
  • 17. Option Strict  Option Strict – Set to On or Off. – Default : off – Used normally when working with conversions in code. – Option Strict is prevents program from automatic variable conversions, that is implicit data type conversions .
  • 18. Option Strict – If Option is on and you assign a value of one type to a variable of another type Visual Basic will consider error. – There is any possibility of data loss, as when you're trying to assign the value in a variable to a variable of less precise data storage capacity. – In that case, you must use explicit conversion.  CODE
  • 19. Option Compare  Default : Binary.  Binary - Optional - compares based on binary representation - case sensitive  Text - Optional - compares based on text representation - case insensitive  Code
  • 20. Type Conversion  In Visual Basic, data can be converted in two ways: – Implicitly (widening), which means the conversion is performed automatically, – Explicitly(narrowing), which means you must perform the conversion.
  • 21.  Implicit Conversions (widening Conversion)  Widening conversion is one where the new data is always big enough to hold the old datatype’s value.  For example – Long is big enough to hold any integer. – Copying an integer value in to long variable is widening conversion.
  • 22. Example Module Module1 Sub Main() Dim d=132.31223 as Double Dim i as Integer i=5 i=d d=i Console.WriteLine("Integer value is" & i) End Sub End Module
  • 23. Explicit Conversions (Narrowing Conversion) – When types cannot be implicitly converted you should convert them explicitly. – This conversion is also called as cast. – Explicit conversions are accomplished using CType function. i = CType(d, Integer) or i=CInt(d) Code
  • 24. Example Module Module1 Sub Main() Dim d As Double d = 132.31223 Dim i As Integer i = CType(d, Integer) 'two arguments, type we are converting 'from, to type desired Console.WriteLine("Integer value is " & i) Console.ReadKey() End Sub End Module
  • 25. CType Below is the list of conversion functions which we can use in VB .NET.  CBool— Convert to Bool data type.  CByte— Convert to Byte data type.  CChar— Convert to Char data type.  CDate— Convert to Date data type.  CDbl— Convert to Double data type.  CDec— Convert to Decimal data type.  CInt— Convert to Int data type.  CLng— Convert to Long data type.  CObj— Convert to Object type.  CShort— Convert to Short data type.  CSng— Convert to Single data type.  CStr— Convert to String type.
  • 26. Operators An operator is a symbol used to perform operation on one or more operands. Syntax Oper1=oper2 operator oper3 Example Sum=a+b
  • 27. Operators Arithmetic Operators Operator Use ^ Exponentiation - Negation (used to reverse the sign of the given value, exp -intValue) * Multiplication / Division Integer Division Mod Modulus Arithmetic + Addition - Subtraction
  • 28. Operators Concatenation Operators Operator Use + String Concatenation & String Concatenation
  • 29. Difference Preview / operator operator It is used for Division It is used for Integer Division e.g. Dim a As Integer a = 19 / 5 Result : 4 e.g. Dim a As Integer a = 19 5 Result : 3
  • 30. Operators Comparison Operators Operator Use = Equality <> Inequality < Less than > Greater than >= Greater than or equal to <= Less than or equal to
  • 31. Operators Logical / Bitwise Operators Operator Use Not Negation And Conjunction AndAlso Conjunction Or Disjunction OrElse Disjunction Xor Disjunction
  • 32. Operator Precedence 1. Arithmetic operators have the highest precedence and are arranged this way, from highest precedence to lowest: – Exponentiation (^) – Negation (-) (for example, -intValue reverses the sign of the value in intValue) – Multiplication and division (*, /) – Integer division () – Modulus arithmetic (Mod) – Addition and subtraction (+,-) 2. Concatenation operators: – String concatenation (+) – String concatenation (&)
  • 33. Operator Precedence 3. Comparison operators, which all have the same precedence and are evaluated from left to right – Equality (=) – Inequality (<>) – Less than, greater than (<,>) – Greater than or equal to (>=) – Less than or equal to (<=) 4. Logical/Bitwise operators, which have this precedence order, from highest to lowest: – Negation-(Not) – Conjunction-(And,AndAlso) – Disjunction-(Or, OrElse, Xor)
  • 34. Flow control in VB:  Conditional Statement  Selection statement  Iteration statement  jump statement
  • 35. Conditional Statements  If....Else statement  Syntax If condition Then [statements] Else If condition Then [statements] - - Else [statements] End If
  • 36. Example Module Module1 Sub Main() Dim a,b As Integer If a=b Then Console.WriteLine(“a equal to b”) ElseIf a<b Then Console.WriteLine(“a less than b") Else Console.WriteLine(" a greater than b") End If Console.ReadKey() End Sub End Module
  • 37. Select....Case Statement  It is used to avoid long chains of If….Then….ElseIf statement.  It compare one specific variable against several constant expressions then we use select….case statement.
  • 38. Select Statements  The syntax of the Select Case statement Select Case test_expression Case expressionlist-1 statements-1 Case expressionlist-n statements-n. . . Case Else else_statements End Select
  • 39. Example Module Module1 Sub Main() Dim i As Integer Console.WriteLine("Enter a number between 1 and 4") i = Val(Console.ReadLine()) Select Case i Case 1 Console.WriteLine("You entered 1") Case 2 Console.WriteLine("You entered 2") Case Else Console.WriteLine("You entered >2") End Select Console.ReadKey() End Sub End Module
  • 40. Iteration Statement For Loop  The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes.  The syntax for the For loop looks like this: For index=start to end [Step stepvalue] [statements] Next[index]
  • 41. Example Module Module1 Sub Main() Dim d As Integer For d = 0 To 2 Console.WriteLine("In the For Loop") Next d End Sub End Module
  • 42. While loop  It runs set of statements as long as the conditions specified with while loop is true.  The syntax of while loop looks like this: While condition [statements] End While
  • 43. Example Module Module1 OUTPUT Sub Main() Dim d, e As Integer d = 0 e = 6 While e > 4 e -= 1 d += 1 End While Console.WriteLine("The Loop run " & e & "times") End Sub End Module
  • 44. Do Loop Do[{while | Until} condition] [statements] [Exit Do] [statements] Loop  The Do loop can be used to execute a fixed block of statements indefinite number of times.  The Do loop keeps executing it's statements while or until the condition is true.  The syntax of Do loop looks like this: Do [statements] [Exit Do] [statements] Loop [{while | Until} condition]
  • 45. Example Module Module1 Output Sub Main() Dim str As String Console.WriteLine("What to do?") str = Console.ReadLine() Do Until str = "Cool" Console.WriteLine("What to do?") str = Console.ReadLine() Loop Console.ReadKey() End Sub End Module
  • 46. Example  Write a console application to find out n!.(use for loop)  Write a console application to find out sum of the digits. – i.e. 1237 : 1+2+3+7 = 13.(using while condition)  Write a program to enter marks of student and calculate grade of the student.
  • 47. Procedure  They are a series of statements that are executed when called.  There are two types of procedure in VB .NET: – Function : Those that return a value. – Subroutines (Procedure) : Those that do not return a value.
  • 48. Sub Procedure  Sub procedures are methods which do not return a value.  Each time when the Sub procedure is called the statements within it are executed until the matching End Sub is encountered.  Sub Main(), the starting point of the program itself is a sub procedure.  Sub routine can be created in module and class.  Default access modifier is public.
  • 49. Syntax [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [Access_Specifiers] Sub ProcedureName[(argument list)] [ statements ] [ Exit Sub ] [ statements ] End Sub Code
  • 50.  Access_Specifiers : Public | Protected | Friend | Protected Friend | Private  Attribute List - List of attributes for this procedure. You separate multiple attributes with commas. – ByVal : Pass by value – ByRef : Pass by Reference.  Procedure Name: Name of the Procedure  Exit Sub : Explicitly exit a sub procedure.
  • 51.  Overloads : it indicates that there are other procedure in the class with the same name but with different argument.  Overrides :-Specifies that this Sub procedure overrides a procedure with the same name in a base class.  Overridable : -Specifies that this Sub procedure can be overridden by a procedure with the same name in a derived class.  NotOverridable:- Specifies that this Sub procedure may not be overridden in a derived class.  MustOverride:-Specifies that this Sub procedure is not implemented in class and must be implemented in a derived class.
  • 52. Function  Function is a method which returns a value.  Functions are used to evaluate data, make calculations or to transform data.  Functions are declared with the Function keyword.
  • 53. Syntax [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [Access_Specifiers] Function Func_name[argument List ] [ As type ] [ statements ] [ Exit Function ] [statements ] End Function
  • 54.  Type- Data type of the value returned by the Function procedure can be – Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String;  Access_Specifiers : Public | Protected | Friend | Protected Friend | Private  Code
  • 55. Example  The calculate_Amount sub routine takes the quantity and unit price of product and calculate the total amount.  The calculate_Amount sub routine takes the quantity and unit price of product and return total amount.
  • 56. Array  It is a collection of elements of same datatype.  It access using single name and index number.  This is very useful when you are working on several pieces of data that all have the same variable datatype & purpose.
  • 57. Type of Array Demo  One dimensional Dim Array_name(size) as Datatype e. g. Dim name(20) As String Dim Array_name() as Datatype=new data type(size){list of constant separated by comma} e.g. Dim num() as integer=New integer(5) {1,2,3,4,5}  Multidimensional e. g. Dim matrix(3,3) As Integer Dim mat(,) as Integer=New Integer(3,3) Dim matrix(,) As Integer =New Integer(){{2,2},{0,0},{1,3}}
  • 58. Dynamic Array  You can resize an array using ReDim Keyword.  Syntax ReDim [Preserve] Array_name(new Size)  If you use ReDim statement then existing content are erased.  If you want to preserve existing data when reinitializing an array then you should use the Preserve keyword .
  • 59. Dim Test() as Integer={1,3,5} 'declares an array an initializes it with three members ReDim Test(25) 'resizes the array and lost existing data. ReDim Preserve Test(25) 'resizes the array and retains the data in elements 0 to 2 Demo
  • 60. Function In Array Function Description GetLength Get length of the array GetType Get Datatype of an array First It gets the first element of an array. Last It gets the last element of an array. Max It gets the Maximum element of an array. Min It gets the Minimum element of an array.
  • 61. For Each……Next Loop This element automatically loops over all the element in array or collection. No need to write starting or ending index. Syntax For Each element in group [statement] [Exit For] [Statement] Next [Element] Example
  • 62. Difference For For Each The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for Each statement repeats a group of embedded statements for each element in an array or an object collection. Need to specify the loop bounds No not need to specify the loop bounds minimum or maximum Syntax : For index=start to end [Step] [statements] [statements] Next[index] Syntax : For Each element in group [statement] [Exit For] [Statement] Next [Element]
  • 63. Difference While Until "do while" loops while the test case is true. “do until ” loops while the test case is false. Syntax : Do while condition [statements] [Exit Do] [statements] Loop Syntax : Do Until condition [statements] [Exit Do] [statements] Loop
  • 64. String Function Code To Do This To USE Concatenate two strings &, +, String.Concat, String.Join Compare two strings StrComp Return Zero if same else 1 String.Compare Return zero if same else 1 String.Equals Return true if same else false String.CompareTo Return Zero if same else false Convert strings CStr, String. ToString Copying strings =, String.Copy Convert to lowercase or uppercase Lcase, Ucase, String. ToUpper, String. ToLower
  • 65. String Function To Do This To USE Create an array of strings from one string String.Split Find length of a string Len, String.Length Get a substring Mid, String.SubString Insert a substring String.Insert Remove text String.Remove Replace text String.Replace
  • 66. String Function To Do This To USE Search strings InStr, String.Chars, String.IndexOf, String.LastIndexOf, Trim leading or trailing spaces (Remove Unwanted space) LTrim, RTrim, Trim, String.Trim, String.TrimEnd, String.TrimStart Work with character codes Asc, Chr
  • 67. Enumeration Access Modifier : (Optional) Public, Protected, Friend, Private [ access modifier ] Enum enumeration_name [ As data type ] member list End Enum
  • 68. Example Enum Days Demo Monday=1 Tuesday=2 Wednesday=3 Thursday=4 Friday=5 Saturday=6 Sunday=7 End Enum Sub Main() Console.WriteLine(“Friday is a day” & Days.Friday) End Sub
  • 69. Exception  Exceptions : It is a runtime errors that occur when a program is running and causes the program to abort without execution.  Such kind of situations can be handled using Exception Handling.  Exception Handling : – By placing specific lines of code in the application we can handle most of the errors that we may encounter and we can enable the application to continue running.
  • 70.  VB .NET supports two ways to handle exceptions, – Unstructured exception Handling – using the On Error goto statement – Structured exception handling – using Try....Catch.....Finally 
  • 71. Unstructured Exception Handling  The On Error GoTo statement enables exception handling and specifies the location of the exception- handling code within a procedure.  How the On Error GoTo statement works: On Error GoTo [ lable | 0 | -1 ] | Resume Next Code
  • 72. Statement Meaning On Error GoTo -1 Resets Err object to Nothing, disabling error handling in the routine On Error GoTo 0 Resets last exception-handler location to Nothing, disabling the exception. On Error GoTo <labelname> Sets the specified label as the location of the exception handler On Error Resume Next Specifies that when an exception occurs, execution skips over the statement that caused the problem and goes to the statement immediately following. Execution continues from that point.
  • 73. Structured Exception Handling  On Error Goto method of exception handling sets the internal exception handler in Visual Basic.  It certainly doesn't add any structure to your code,  If your code extends over procedures and blocks, it can be hard to figure out what exception handler is working when.
  • 74.  Structured exception handling is based on a particular statement, the Try…Catch…Finally statement, which is divided into a – Try block, – optional Catch blocks, – and an optional Finally block.
  • 75. Syntax Try //code where exception occurs Catch e as Exception // handle exception Finally // final Statement End Try
  • 76.  The Try block contains code where exceptions can occur.  The Catch block contains code to handle the exceptions that occur.  If an exception occurs in the Try block, the code throws the exception.  It can be caught and handled by the appropriate Catch statement.  After the rest of the statement finishes, execution is always passed to the Finally block, if there is one. Code
  • 77. Exception Object  The Exception object provides information about any encountered exception.  properties of the Exception object: – HelpLink : can hold an URL that points the user to further information about the exception. – InnerException : It returns an exception object representing an exception that was already in the process of being handled when the current exception was thrown.
  • 78. – Message : It holds a string, which is the text message that informs the user of the nature of the error and the best way or ways to address it. – StackTrace : It holds a stack trace, which you can use to determine where in the code the error occurred.
  • 79. Standard Exception Exception Type Description Exception Base type for all exceptions IndexOutOfRangeException Thrown when you try to access an array index improperly NullReferenceException Thrown when you try to access a null reference InvalidOperationException Thrown when a class is in an invalid state ArgumentException Thrown when you pass an invalid argument to a method ArithmeticException Thrown for general arithmetic errors
  • 80. Difference VALUE TYPE REFERENCE TYPE Value type they are stored on stack Reference type they are stored on heap When passed as value type new copy is created and passed so changes to variable does not get reflected back When passed as Reference type then reference of that variable is passed so changes to variable does get reflected back Value type store real data Reference type store reference to the data. Value type consists of primitive data types, structures, enumerations. Reference type consists of class, array, interface, delegates Value types derive from System.ValueType Reference types derive from System.Object