unit 2 vb variables
TRANSCRIPT
-
8/13/2019 Unit 2 VB Variables
1/111
Vipul J JoshiNarsinhbhai Institute of Computer Studies and Management(NICM)
Kadi
-
8/13/2019 Unit 2 VB Variables
2/111
A storage location in memory (RAM)
Holds data/information while the program is running
These storage locations can be referred to by their
names
Every variable has three properties:
Name- reference to the location - cannot be changed
Value- the information that is stored - can be changedduring program execution, hence the name variable
Data Type- the type of information that can be stored -
cannot be changed
-
8/13/2019 Unit 2 VB Variables
3/111
You the programmer make up a name for thevariable
Visual Basic associates that name with alocation in the computer's RAM
The value currently associated with thevariable is stored in that memory location
You simply use the name you choose whenyou need to access the value
-
8/13/2019 Unit 2 VB Variables
4/111
Copy and store values entered by the user Perform arithmetic manipulation on values
Test values to see if they meet a criteria Temporarily hold and manipulate the value of
a control property Hold data/information so that it can be
recalled for use at a later point in the code
-
8/13/2019 Unit 2 VB Variables
5/111
Data type - Specifies type of data variable can store Integer variables: Long, Integer, Short, Byte Floating-point variables: Single, Double
Fixed decimal point variable: Decimal Boolean variables: True, False
Character variable: Char
Text variable: String
The Object variable Default data type assigned by Visual Basic
Can store many different types of data
Less efficient than other data types
-
8/13/2019 Unit 2 VB Variables
6/111
Data type Prefix Size ValuesByte byt 1 byte positive integer value from 0 to 255Short shr 2 byte integer from 32,768 to +32,767Integer int 4 byte integer from +/- 2,147,483,647
Long lng 8 byte integer from +/- 9,223,372,036,854,775,807Single sng 4 byte single-precision, floating-point numberDouble dbl 8 byte double-precision, floating-point numberDecimal dec 16 byte number with up to 28 significant digits
Char chr 2 byte Any single characterBoolean bln 2 byte True or False
String str (4 byte) Text - Any number/combination of charactersDate dtm 8 byte 8 character date: #dd/mm/yyyy#Object obj (4 byte) An address that refers to an object
-
8/13/2019 Unit 2 VB Variables
7/111
First character must be a letter or underscore Must contain only letters, numbers, and
underscores (no spaces, periods, etc.)
Can have up to 255 characters Cannot be a VB language keyword Naming Conventions Should be meaningful
Follow 3 char prefix style - 1st 3 letters in lowercaseto indicate the data type
After that, capitalize the first letter of each word
Example: intTestScore
-
8/13/2019 Unit 2 VB Variables
8/111
A variable declaration is a statement thatcreates a variable in memory
Syntax: Dim VariableNameAs DataType Dim (short for Dimension) - keyword
VariableName - name used to refer to variable
As - keyword DataType - one of many possible keywords to
indicate the type of value the variable will contain
Example: Dim intLength as Integer
-
8/13/2019 Unit 2 VB Variables
9/111
A starting or initialization value may bespecified with the Dim statement
Good practice to set an initial value unlessassigning a value prior to using the variable Syntax:
Dim VariableNameAs DataType= Value Just append " = value to the Dim statement
= 5assigning a beginning value to the variable
Example: Dim intLength as Integer = 5
-
8/13/2019 Unit 2 VB Variables
10/111
Variable MUST be declared prior to the codewhere they are used
Variable should be declared first in theprocedure (style convention)
Declaring an initial value of the variable in thedeclaration statement is optional
Refer to default values (next slide)
-
8/13/2019 Unit 2 VB Variables
11/111
Data type Default (Initial) value
All numeric types Zero (0)
Boolean FalseChar Binary 0
String or Object Empty
Date 12:00 a.m. on January 1, 0001
-
8/13/2019 Unit 2 VB Variables
12/111
Actual value/data/information Similar to a variable, but can NOT change
during the execution of a program. Examples of Literals:
Numeric: 5 ; 157 ; 195.38256
String: Paul ; Hello!!! ; Jackson, AL 36545
Char: a ; 1 ; ? ; @
Boolean: True ; False
-
8/13/2019 Unit 2 VB Variables
13/111
Programs often need to use given values
For example: decTotal *= 1.06
Adds 6% sales tax to an order total
Two problems with using literals for these typesof values
The reason for multiplying decTotal by 1.06 isnt
always obvious
If sales tax rate changes, must find and change every
occurrence of .06 or 1.06
-
8/13/2019 Unit 2 VB Variables
14/111
Use of named constantsresolves both these issues Can declare a variable whose value is set at
declaration and cannot be changed later: Syntax: Const CONST_NAMEAs DataType= Value
Looks like a normal declaration except:
Const used instead of Dim
An initialization value is required
By convention, entire name capitalized with underscore
characters to separate words
-
8/13/2019 Unit 2 VB Variables
15/111
The objective of our code is now clearer
Const sngSALES_TAX_RATE As Single = 1.06
decTotal *= sngSALES_TAX_RATE Can change all occurrences in the code simply
by changing the initial value set in thedeclaration
If tax rate changes from 6% to 7%
Const sngSALES_TAX_RATE As Single = 1.07
-
8/13/2019 Unit 2 VB Variables
16/111
What Indicates the part of the program where thevariable can be used
When From the variable declaration until the end ofthe code block (procedure, method, etc.) where it is
declared Variable cannot be used before it is declared
Variable declared within a code block is only visible tostatements within that code block
Called Local Variable Can be declared at the beginning of the class code window
(General Declarations section) and be available to all blocks Called Form Level Variable
Variables that share the same scope cannot have the samename (same name ok if different scope)
-
8/13/2019 Unit 2 VB Variables
17/111
What Indicates the part of the program where the
variable exists in memory When From the beginning of the code block
(procedure, method, etc.) where it is declared untilthe end of that code block
When the code block begins the space is created to holdthe local variables
Memory is allocated from the operating system When the code block ends the local variables are destroyed
Memory is given back to the operating system
-
8/13/2019 Unit 2 VB Variables
18/111
Syntax: variablename = expression Assigns the value of the expression to the
variable. (The variable must be on the left andthe expression on the right.)
Example: intNumber1 = 4
intNumber2 = 3 * (2 + 2) intNumber3 = intNumber1
IntNumber1 = intNumber1 + 6
-
8/13/2019 Unit 2 VB Variables
19/111
A value of one data type can be assigned to a variable
of a different type
An implicit type conversion is an attempt to automatically
convert to the receiving variables data type A widening conversion suffers no loss of data
Converting an integer to a single
Dim sngNumber as Single = 5
A narrowing conversion may lose data Converting a decimal to an integer
Dim intCount = 12.2 intCount becomes 12
-
8/13/2019 Unit 2 VB Variables
20/111
VB provides a set of functions that perform data type
conversions These functions will accept a literal, variable name, or
arithmetic expression The following narrowing conversions require an
explicit type conversion
Double to Single
Single to Integer Long to Integer
Boolean, Date, Object, String, and numeric types
represent different sorts of values and require
conversion functions as well
-
8/13/2019 Unit 2 VB Variables
21/111
-
8/13/2019 Unit 2 VB Variables
22/111
Ctype Usage
CBool Convert to Booldata type
CByte Convert to Bytedata type
CChar Convert to Chardata type
CDate Convert to Datedata type
CDbl Convert to Doubledata type
CDec Convert to Decimaldata type
CInt Convert to Intdata type
CLng Cpnvert to LongtypeCObj Convert to Objecttype
CShort Convert to Shortdata type
CSng Convert to Singledata type
CStr Convert to Stringtype
CType (converting Var,Datatype)
CType is compiled in-line, meaning theconversion code is part of the code thatevaluates the expression. Execution is fasterbecause there is no call to procedure toperform the conversion
-
8/13/2019 Unit 2 VB Variables
23/111
The Val functionis a more forgiving means ofperforming string to numeric conversions
Uses the form Val(string) If the initial characters form a numeric value,
the Val function will return that Otherwise, it will return a value of zero
-
8/13/2019 Unit 2 VB Variables
24/111
Val Function Value Returned
Val("34.90) 34.9
Val("86abc) 86
Val("$24.95) 0
Val("3,789) 3
Val(") 0
Val("x29) 0
Val("47%) 47
Val("Geraldine) 0
-
8/13/2019 Unit 2 VB Variables
25/111
Returns a string representation of the value inthe variable calling the method
Every VB data type has a ToString()method Uses the form VariableName.ToString For example
Dim number as Integer = 123lblNumber.text = number.ToString
Assigns the string 123 to the text property of the
lblNumber control
-
8/13/2019 Unit 2 VB Variables
26/111
-
8/13/2019 Unit 2 VB Variables
27/111
Dim Amnt As Single = 9959.95
Dim strAmnt As String
strAmnt = Amnt.ToString(C)Or use the following picture numeric format string:
strAmnt = Amnt.ToString($#,###.00)
Output:
Both statements will format the value as $9,959.95.
-
8/13/2019 Unit 2 VB Variables
28/111
-
8/13/2019 Unit 2 VB Variables
29/111
-
8/13/2019 Unit 2 VB Variables
30/111
Dim Amount As Decimal = 42492.45
Debug.WriteLine(Amount.ToString($#,###.00))
$42,492.45
Amount = 0.2678
Debug.WriteLine(Amount.ToString(0.000))
0.268
Amount = -24.95
Debug.WriteLine(Amount.ToString
($#,###.00;($#,###.00)))
($24.95)
-
8/13/2019 Unit 2 VB Variables
31/111
We used variables to store individual values. As a matter offact, most programs store sets of data of different types. Forexample, a program for balancing your checkbook must
store several pieces of information for each check: thechecksnumber, amount, date, and so on. All these pieces ofinformation are necessary to process the checks, and ideally,they should be stored together.
You can create custom data types that are made up of
multiple values using structures. A VB structure allowsyou to combine multiple values of the basic data types andhandle them as a whole. For example, each check in acheckbook-balancing application is stored in a separate
structure
-
8/13/2019 Unit 2 VB Variables
32/111
Syntax:[ Public | Protected | Friend | Protected Friend |Private]
Structure structName
Dim variable1 As varTypeDim variable2 As varType
...
Dim variablen As varType
End Structure
In the above syntax structName is the name of the user defined datatype,that follows the naming convention of a variable. Publicoption makes thesedatatypes available in all projects, modules, classes. If declared Private theuser defined datatypes can be used where it is declared, same applies toFriendand Protected Friend. variable1is the name of the element of an userdefined datatype. typeis the primitive datatype available in visual basic
-
8/13/2019 Unit 2 VB Variables
33/111
Example:Structure Empdetails
Dim EmpNo As Integer
Dim EmpName As String
Dim EmpSalary As IntegerDim EmpExp As Integer
End Structure
*Event Scope
Dim TotalSal As Empdetails
TotalSal.EmpNo = TextBox1.TextTotalSal.EmpName = TextBox2.Text
TotalSal.EmpSalary = TextBox3.Text
TotalSal.EmpExp = TextBox4.Text
TextBox5.Text = Val(TotalSal.EmpSalary) *
Val(TotalSal.EmpExp)*End of Event Scope
-
8/13/2019 Unit 2 VB Variables
34/111
A standard structure for storing data in anyprogramming language is the array.
Whereas individual variables can hold singleentities, such as one number, one date, orone string
Arrays can hold sets of data of the same type(a set of numbers, a series of dates, and soon). An array has a name, as does a variable,and the values stored in it can be accessed by
an index.
-
8/13/2019 Unit 2 VB Variables
35/111
Unlike simple variables, arrays must bedeclared with the Dim (or Public) statement
followed by the name of the array and theindex of the last element in the array inparenthesesfor example:
Dim intSalary(15) as Integer
It holds the value of 16 persons. To assignvalues you can write
intSalary(0) = 25000
-
8/13/2019 Unit 2 VB Variables
36/111
Arrays, like variables, are not limited to thebasic data types. You can declare arrays thathold any type of data, including objects.
The other way to store multiple values is byusing structure
Dim colors(2) As Colorcolors(0) = Color.BurlyWood
colors(1) = Color.AliceBlue
colors(2) = Color.Sienna
Structure Employee
Dim Name As String
Dim Salary As Decimal
End Structure
Dim Emps(15) As Employee
Emps(2).Name = Hello All
Emps(2).Salary = 62000
-
8/13/2019 Unit 2 VB Variables
37/111
Just as you can initialize variables in the sameline in which you declare them, you can
initialize arrays, too, with the followingconstructor.Dim arrayname() As type = { entry0, entry1, ...
entryN }
Dim Names() As String = {Hello,All}
This statement is equivalent to the followingstatements
Dim Names(1) As String
Names(0) = Hello
Names(1) = All
-
8/13/2019 Unit 2 VB Variables
38/111
The first element of an array has index 0. The number thatappears in parentheses in the Dimstatement is one fewer than
the arraystotal capacity and is the arraysupper limit (or upper
bound). The index of the last element of an array (its upperbound) is given by the method GetUpperBound, which
accepts as an argument the dimension of the array and returnsthe upper bound for this dimension. The arrays we examined sofar are one-dimensional and the argument to be passed to the
GetUpperBound method is the value 0. The total number ofelements in the array is given by the method GetLength,
which also accepts a dimension as an argument. The upperbound of the following array is 19, and the capacity of the array
is 20 elements:
-
8/13/2019 Unit 2 VB Variables
39/111
Dim Names(19) As Integer
The first element is Names(0), and the last isNames(19).
Debug.WriteLine(Names.GetLowerBound(0))Output: 0
Debug.WriteLine(Names.GetUpperBound(0))
Output: 19
You can also use length() property of arrayto retrieve the count of element
-
8/13/2019 Unit 2 VB Variables
40/111
Dim a(,) As Integer = {{10, 20, 30}, {11, 21, 31},
{12, 22, 32}}
Console.WriteLine(a(0, 1)) will print 20
Console.WriteLine(a(2, 2)) will print 32
Debug.WriteLine(numbers.Rank
)2 dimensions in array
-
8/13/2019 Unit 2 VB Variables
41/111
Dynamic arrays are array that are declaredusing a Dim statement with blank parenthesis
initially and are dynamically allocateddimensions using the Redimstatement. ThePreserve keyword is used with Redim
to preserve the existing elements intake.
-
8/13/2019 Unit 2 VB Variables
42/111
Module Module1
Sub Main()
Dim a() As Integer = {2, 2}
Dim i, j As Integer
Console.WriteLine("Array before Redim")
For i = 0 To a.GetUpperBound(0)Console.WriteLine(a(i))
Next
ReDim Preserve a(5)
Console.WriteLine("Array after Redim")
For j = 0 To a.GetUpperBound(0)
Console.WriteLine(a(j))
Next
Console.ReadLine()
End Sub
End Module
-
8/13/2019 Unit 2 VB Variables
43/111
Arithmetic Operators
^ Exponential
* Multiplication
/ Floating Point Division
\ Integer Division
MOD Modulus (remainder from division)
+ Addition
Subtraction
& String Concatenation (putting them together)
-
8/13/2019 Unit 2 VB Variables
44/111
Examples of use: decTotal = decPrice + decTax
decNetPrice = decPrice - decDiscount
dblArea = dblLength * dblWidth
sngAverage = sngTotal / intItems
dblCube = dblSide ^ 3
-
8/13/2019 Unit 2 VB Variables
45/111
The backslash (\) is used as an integer divisionoperator
The result is always an integer, created bydiscarding any remainder from the division
Example intResult = 7 \ 2 result is 3
shrHundreds = 157 \ 100 result is 1 shrTens = (157 - 157 \ 100 * 100) \ 10
result is ?
-
8/13/2019 Unit 2 VB Variables
46/111
This operator can be used in place of thebackslash operator to give the remainder of a
division operationintRemainder = 17 MOD 3 result is 2
dblRemainder = 17.5 MOD 3 result is 2.5
Any attempt to use of the \ or MOD operatorto perform integer division by zero causes aDivideByZeroException runtime error
-
8/13/2019 Unit 2 VB Variables
47/111
Concatenate: connect strings together Concatenation operator: the ampersand (&) Include a space before and after the & operator
Numbers after & operator are converted to strings
How to concatenate character strings strFName = "Bob"
strLName = "Smith"
strName = strFName & " Bob
strName = strName & strLName Bob Smith
intX = 1 intY = 2
intResult = intX + intY
strOutput = intX & + & intY & = & intResult 1 + 2 = 3
-
8/13/2019 Unit 2 VB Variables
48/111
-
8/13/2019 Unit 2 VB Variables
49/111
Operatorprecedencetells us the order in whichoperations are performed
From highest to lowest precedence:
Exponentiation (^) Multiplicative (* and /)
Integer Division (\)
Modulus (MOD)
Additive (+ and -) Parentheses override the order of precedence Where precedence is the same, operations
occur from left to right
-
8/13/2019 Unit 2 VB Variables
50/111
Parenthesis Exponential
Multiplication / Division Integer Division MOD Addition / Subtraction String Concatenation Relational Operators (< , > , >= ,
-
8/13/2019 Unit 2 VB Variables
51/111
6 * 2 ^ 3 + 4 / 2 = 50
7 * 4 / 26 = 8
5 * (4 + 3)15 Mod 2 = 34
intX = 10
intY = 5
intResultA = intX + intY * 5 'iResultA is 35
iResultB = (intX + intY) * 5 'iResultB is 75 dResultA = intX - intY * 5 'dResultA is -15 dResultB = (intX - intY) * 5 'dResultB is 25
-
8/13/2019 Unit 2 VB Variables
52/111
-
8/13/2019 Unit 2 VB Variables
53/111
It will execute some logic when a conditionbecome true goes to If and some other logic
when the condition is false goes to Else. It is always perform results for comparison of
two values.Ifcondition Then
Logic...ElseIfcondition-n Then
Logic...
Else
Logic....
End If
-
8/13/2019 Unit 2 VB Variables
54/111
If IsNumeric(txtNo.Text) ThenlblAns.Text = Yes its Numeric
End If
If txtNo.Text Mod 2 =0 Then
lblAns.Text = Its Even
ElselblAns.Text = Its Odd
End If
n1= txtNo1.Text
n2= txtNo2.Text
If no1 > no2 ThenlblAns.Text = no1 & Big
ElseIf no2>no1 Then
lblAns.Text = no2 &Big
ElselblAns.Text = Both Equal
End If
Use with Logical Operators
If no110 Then
lblAns.Text = Its Ok
ElselblAns.Text =Not Good
End If
-
8/13/2019 Unit 2 VB Variables
55/111
When we are comparing the same expression with
several values , then we can use Select....Case
statement as and alternative of If...Then...Else
We can use the To keyword for range of values We can also use Iskeyword for specific comparision
SelectCaseexpression
Case expression-n
LogicCaseElse
Logic
EndSelect
-
8/13/2019 Unit 2 VB Variables
56/111
-
8/13/2019 Unit 2 VB Variables
57/111
Looping structure are used when a group ofstatements is to be executed repeatedly untila condition become True or False
VB.Net supports the follwoing loopstructures
For Next
Do Loop
While End While
For each Next
-
8/13/2019 Unit 2 VB Variables
58/111
The For loop executes a block of statements aspecific number of time
Remember that Next keyword should be used
in For....Next at the end.
Forcounter = start Toend [Stepincrement/decrement]Logic
Next
-
8/13/2019 Unit 2 VB Variables
59/111
Dim I as Integer
For I=0 To 10 Step 1
Logic...
NextDim I as Integer
For I=0 To 10Logic...
Next
Dim I as Integer
For I=50 To 1 Step -2
Logic...
Next
Dim I,J,K as Integer
For I=1 To 50
For J=1 To 30
For K=1 To 10
Logic...
Next Next Next
Dim I,J as Integer
For I=1 To 50
For J=1 To 30
Logic...
Next J,I
Dim I as IntegerFor I=1 To 100 Step 2
Next
-
8/13/2019 Unit 2 VB Variables
60/111
While loop keeps executing until thecondition against which it tests remain true.
The While statement always checks thecondition before it begins the loop.
In While loop programmer have to maintainor keep track of increment or decrement
value.Whilecondition
Logic
EndWhile
Dim no As Integer=5
While no>0
MsgBox(no)
no=no-1
End While
-
8/13/2019 Unit 2 VB Variables
61/111
Repeats a block of statments while a Booleancondition is False or until the conditionbecomes True.
We can use either While or Until. While: Repeat loop until condition is False. Until: Repeat the loop until condition is True.
Do{While| Until} condition
Logic.........
Loop
Do
Logic.........
Loop{While| Until} condition
-
8/13/2019 Unit 2 VB Variables
62/111
-
8/13/2019 Unit 2 VB Variables
63/111
-
8/13/2019 Unit 2 VB Variables
64/111
Dim ctl As new ControlDim cnt As Integer
For Each ctl Inme.Controls
If TypeOfctl Is TextBox Then
cnt = cnt +1
End If
Next
MsgBox(cnt)
TypeOf....Is Operator:
This operator is chechked first parameter withsecond type that whether given object is and
object of Is a given class.
-
8/13/2019 Unit 2 VB Variables
65/111
This is not a type of Loop Executes a series of statements making
repeated reference to a single object. The use of it do not require calling a name of
object again and again. To make this type of code more efficient and
easier to read, we use this blockWithobjectName
Logic
EndWith
-
8/13/2019 Unit 2 VB Variables
66/111
// Setting up properties of my button by using codeWith btnAns
.Text = Click Me
.ForeColor = Color.Green
.BackColor = Color.White
.Height= 50
.Width=100
End With
-
8/13/2019 Unit 2 VB Variables
67/111
A procedure is a set of one or more program statements that can
be run or call by referring to the procedure name.
Divide the big program into small procedures
An application is easier to debug and easy to find error.
Reusability of code. Two types of procedures are In-builtor User- defined procedure.
VB.Net have following type of procedures
Sub proceduresdoes not return value.
Event-handling procedures are sub procedure that execute inresponse to an event is triggered(Button1_Click)
Function procedures return a value
Property proceduresused in object oriented concept
-
8/13/2019 Unit 2 VB Variables
68/111
-
8/13/2019 Unit 2 VB Variables
69/111
Public Class SubProdedure
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Hi(12, 15) // call Hi(12,15)
Sub Hi(ByVal a As Integer, ByVal b As Integer)
MsgBox("Hello I am Here " & "" + (a + b).ToString)
End Sub
End Class
-
8/13/2019 Unit 2 VB Variables
70/111
A Function procedure is similar to a subprocedure, but it return a value to the callingprogram.
Function may or may not have argument By Val is by default argument type As clause is written after the parameter list is
set. It return a value so call function using:
varname= functionName(argument)
By default function are public
-
8/13/2019 Unit 2 VB Variables
71/111
[Modifiers] FunctionFunctionName [(ParameterList)]
AsReturnType
Statements
Return Values]
End Function
Function add(ByVal s1 As Integer, ByVal s2 As Integer)
As Integer
Return s1 + s2
End Function
-
8/13/2019 Unit 2 VB Variables
72/111
We can specify procedure argument as an optionallike in C++ (default argument)
Its not compulsory to pass for calling it
It should be indicate by Optional keyword with
default value other wise it overwritten with defaultvalue.
Optional argument must be at last declareFunction add(ByVal s1 As Integer, Optional ByVal s2 As Integer =1)
As IntegerReturn s1 + s2
End Function
-----------------------------------------------------------------
Sub ad(ByVal s As Integer, Optional ByVal v As Integer = 1)
MsgBox(s + v)
End Sub
-
8/13/2019 Unit 2 VB Variables
73/111
There are two ways to pass arguments:
By Val (By Value) Default in VB.NET
By Ref (By Reference) By Val: refers to pass a copy of a variable to
procedure. We can make changes to the copyand the original will notbe altered. Variable
itself will not change with in the procedure By Ref: refers to actual argument(memory
address) itself is passed for the same variable
and arguments
-
8/13/2019 Unit 2 VB Variables
74/111
Sub Button ClickDim x,y As Integer
x= txt1.Texty= txt2.TextSwap(x,y)
txt3.Text = xtxt4.Text=y
End Sub
Sub Swap(By Val a As Integer,By Val b As Integer)Dim temp As Integer
temp=aa=bb=temp
End Sub
-
8/13/2019 Unit 2 VB Variables
75/111
3 ways to pass arguments
Passing Args. by Position(Ordered)
Passing Args. by Name (Use varname and :) Mixing Args. by Position and by Name
-
8/13/2019 Unit 2 VB Variables
76/111
FO is the implementation of Polymorphismconcept of the OOP.
In VB.Net we can declare two or moreprocedure with same name
When we declare more than one prodedurewith the same name but number argument
may be differing, types of arguments may bediffer or sequence of thoes argument may bediffer.
-
8/13/2019 Unit 2 VB Variables
77/111
Private Sub btn_Click()
add(...........)
End Sub
----------------
Sub add()
logic
End Sub------------------
Sub add(ByVal no As Integer)
logic
End Sub
------------------
Sub add(ByVal no1 As Integer, ByVal no2 As Integer)
logicEnd Sub
-----------------------
Sub add(ByVal no1 As Integer, ByVal no2 As Integer, ByVal no3 As
Integer)
logic
End Sub
-
8/13/2019 Unit 2 VB Variables
78/111
IIF
Returns one of two objects, depending on the
evalution of expression.
Its like Ternary operator in C or C++
IIF(Expression,Truepart,Falsepart)
Example
Dim salary As Integer =50000Dim strAns as String
strAns = IIF(salary>30000,Good,Bad)
MsgBox(StrAns)
-
8/13/2019 Unit 2 VB Variables
79/111
-
8/13/2019 Unit 2 VB Variables
80/111
-
8/13/2019 Unit 2 VB Variables
81/111
StrReverse(string)
Returns a string in which the character order of a
specified string is reversed
ASC(char)
Returns ASCII value for the input character
Chr(int)
Returns the character of that relative ASCII value
-
8/13/2019 Unit 2 VB Variables
82/111
-
8/13/2019 Unit 2 VB Variables
83/111
Length() Compare() Concat() Copy() Equals() Trim() EndsWith() StartsWith() Indexof()
Ucase,Lcase,ToUpper,ToLower
Insert() PadLeft() PadRight() Remove() Replace() Substring()
-
8/13/2019 Unit 2 VB Variables
84/111
Objective of MsgBox is to produce a pop-upmessage box, prompt the user and returns aninteger indicating which button is clicked byuser
MsgBox and InputBox are inbuilt functions.MsgBox(Prompt,Button+Icon Style,Title)
MsgBoxis the Model dialog box MsgBox returns an integer value. The value is
determine by the type of buttons being
clicked by the user. (1-vbOk,2 vbCancel,3 vbAbort, 4 vbRetr ,5 vbI nore, 6 vbYes, 7 vbNo)
-
8/13/2019 Unit 2 VB Variables
85/111
Its an advance version of MsgBox function MessageBox is the class and show is method
of it Show method has more argument then
MsgBox function. It have special argumentfor icon and button
MessageBox.Show(Text,caption,button,icon,default button,options,helpbutton)
-
8/13/2019 Unit 2 VB Variables
86/111
InputBox function is to accept data from theuser.
An InputBox function will display a promptbox where the user can enter a value or amessage in the form of text.
The InputBox function with return a vlaue. We
need to declare the data type for values to beaccepted on the InputBox.
varName= InputBox(Prompt,Title,default_text,x-pos,
y-pos)
-
8/13/2019 Unit 2 VB Variables
87/111
-
8/13/2019 Unit 2 VB Variables
88/111
-
8/13/2019 Unit 2 VB Variables
89/111
-
8/13/2019 Unit 2 VB Variables
90/111
11
2
-
8/13/2019 Unit 2 VB Variables
91/111
-
8/13/2019 Unit 2 VB Variables
92/111
Create new project or Existing Project, Addnew form.
Set the property of mainform
Name= frmMDI or frmMain
Text= Main Form
IsMDIContainer=true
WindowState= Maximized (Set as StartUp form)
-
8/13/2019 Unit 2 VB Variables
93/111
-
8/13/2019 Unit 2 VB Variables
94/111
-
8/13/2019 Unit 2 VB Variables
95/111
What is Error ?
Error is somting that is unexpected.
Types of Error
Syntax (Design Time)
Runtime
Logical
-
8/13/2019 Unit 2 VB Variables
96/111
Exception Handling is an in-built mechanismin .NET to detect and handle run time errors.
Runtime errors are an expensive fact of lifeboth during development and after release asoftware to customers. Errors take time tofind and fix it
The .NET framework contains lots ofstandard exceptions. The exceptions are ariseduring the execution of a program. It can be
because of user, logic or system error.
-
8/13/2019 Unit 2 VB Variables
97/111
If programmer do not provide anymechanism to handle these error theprogram goes to terminates.
There are two way to trap Error
Structured Exception Handling (Newer)
Unstructured Exception Handling (Older)
-
8/13/2019 Unit 2 VB Variables
98/111
We use Try.......Catch......Finally statments. Catch and Finally blocks are optional All the exception are directly or indirectly
inherited from the ExceptionClass. We can Catch all the exception using
Catch ex As Exception block
Exceptionclass is the base class of all exceptionclass hirarchy. exobject of the class is used toaccess (error) the property of Exception class
You can use catch for multiple exception
-
8/13/2019 Unit 2 VB Variables
99/111
ex.ToString() will give the user a large
technical dump of the error that occurred likethe error description with path of the form inwhich error will arise, line of the error, eventname etc.
ex.Message() Will give a more to the
point error message. It display main moral ofthe error.
-
8/13/2019 Unit 2 VB Variables
100/111
In Button Click Event..........Try
Dim intNo1,intNo2 As Integer, ans As Integer
intNo1 = txtNo1.Text
intNo2 = txtNo2.Textans = intNo1+ intNo2
MsgBox(ans,Demo)
Catch ex As Exception
MsgBox(ex.ToString,Error1)MsgBox(ex.Message,Error2)
Finally
MsgBox(Hi i am at Finally part);
End Try
-
8/13/2019 Unit 2 VB Variables
101/111
OutOfMemory Exception NullReference Exception InvalidCast Exception
ArrayTypeMismatch Exception IndexOutOfRange Exception Arithmetic Exception
DivideByZeroException OverFlowException FileNotFoundException DirectoryNotFoundException
-
8/13/2019 Unit 2 VB Variables
102/111
UnStructured Exception are simple but now adays its obsolute in VB.NET programes
There are three way to handle error
On Error GoTo
On Error Resume Next
On Error GoTo 0 (Zero)
-
8/13/2019 Unit 2 VB Variables
103/111
Component Object Model is an interfacestandard for software component introducedby Microsoft in 1993. It is used to enable interprocess communication and dynamic objectcreation in any programming language thatsupports the technology. The term COM is
often used in the software developmentindustry as an umbrella term thatencompasses the OLE, OLE Automation,
ActiveX COM+ and DCOM technologies
-
8/13/2019 Unit 2 VB Variables
104/111
DCOM is Distributed Component ObjectModel.
It is the extension of the COM that allowsCOM components to communicate acrossthe network boundaries.
It can efficiently deploy and administrated
Its an open technology DCOM communications also work between
dissimilar computer hardware and OS
-
8/13/2019 Unit 2 VB Variables
105/111
COM DCOM
COM stands for Component objectmodel
Distributed component object model
COM is on local or on one single
machine
DCOM is a working across several
machinesCOM is used for Desktop Applications DCOM is used Network based
Applications
COM is collection of tools which areexecuted on client side environment
DCOM is a Distributed componentobject Model runs at the given server
COM Components exposes itsinterfaces at interface pointer whereclient access Components interface
DCOM is the protocol which enablesthe s/w components in differentmachine to communicate with eachother through n/w
-
8/13/2019 Unit 2 VB Variables
106/111
Managed Code is what Visual Basic .NET and C#compilers create.
The code, which is developed in .NETframework, is known as managed code. Thiscode is directly executed by CLR with help ofmanaged code execution. Any language that iswritten in .NET Framework is managed code.
Managed code uses CLR which in turns looksafter your applications by managing memory,handling security, allowing cross - language
debugging and so on
-
8/13/2019 Unit 2 VB Variables
107/111
-
8/13/2019 Unit 2 VB Variables
108/111
The code, which is developed outside .NET,Framework is known as unmanaged code.
Applications that do not run under the
control of the CLR are said to be unmanaged,and certain languages such as C++ can beused to write such applications, which, for
example, access low - level functions of theoperating system. Background compatibilitywith code of VB, ASP and COM are examples
of unmanaged code
-
8/13/2019 Unit 2 VB Variables
109/111
Unmanaged code can be unmanaged sourcecode and unmanaged compile code.
Unmanaged code is executed with help of
wrapper classes. Wrapper classes are of two types: CCW (COM
Callable Wrapper)and RCW (Runtime
Callable Wrapper).
-
8/13/2019 Unit 2 VB Variables
110/111
-
8/13/2019 Unit 2 VB Variables
111/111