unit 1 introduction to visual basic programming
DESCRIPTION
TRANSCRIPT
UNIT 1Introduction 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 includes1. Menu Bar2. Standard Toolbar3. Toolbox4. Forms Designer5. Output Window6. Solution Explorer7. Properties Window8. 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 DataTypeVariableName : 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 nameInteger : is the data type
List of Data typesType 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 typesType 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 Module1Sub Main()
Dim d=132.31223 as DoubleDim i as Integer
i=5i=d
d=iConsole.WriteLine("Integer value is" & i)
End SubEnd 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
ExampleModule 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 SubEnd Module
CTypeBelow 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.
SyntaxOper1=oper2 operator oper3
ExampleSum=a+b
Operators Arithmetic OperatorsOperator 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 Precedence1. 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 Precedence3. 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 SubEnd 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 SubEnd Module
Iteration StatementFor 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 IntegerFor d = 0 To 2Console.WriteLine("In the For Loop")Next d
End SubEnd 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
ExampleModule Module1 OUTPUT
Sub Main()Dim d, e As Integerd = 0e = 6While e > 4
e -= 1d += 1
End WhileConsole.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 SubEnd 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 dimensionalDim Array_name(size) as Datatype
e. g. Dim name(20) As StringDim 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
DifferenceFor 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]
DifferenceWhile 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
ExampleEnum Days Demo
Monday=1Tuesday=2Wednesday=3Thursday=4Friday=5Saturday=6Sunday=7
End EnumSub 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 ExceptionException 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