1 - ShyamChawadaDotNet - Book
1 - ShyamChawadaDotNet - Book
NET
INDEX
1. Event driven modal
2. Visual Studio.NET
a. Features of VS.NET
3. Visual Basic.NET
4. What is the .NET Framework?
a. CLR
b. CTS
c. CLS
d. Assembly
e. Metadata
f. FCL
g. Namespace
h. Garbage Collection
i. Execution Process of .NET program.
j. MSIL
k. JIT
5. IDE
6. First program
7. Exercise 1
8. Variable
a. Variable Declaration
b. Naming Convention
c. Data type
d. Variable Initialization
9. Type Conversion
10. Type Checking function
11. Option Explicit and Option Strict
12. Operators
a. Arithmetic
b. Concatenation
c. Assignment
d. Relational
e. Bitwise
f. Miscellaneous
13. IMP
a. Multiple statement in one line
b. One line in multiple statement
c. Startup form
d. Comment
e. Design time and Run time
14. Control Structure
a. If..Then…Else
b. Select…Case
15. Loops
a. For…Next
b. While
c. Do
1
d. For each..Next
16. With..End with
17. IMP
18. Msgbox , MessageBox.Show and InputBox
19. Procedure
a. Modular coding
b. Sub Procedure
c. Function
d. Optional Argument
e. Function Overloading
f. Pass by Val and Pass by Ref
g. Passing Argument
h. Event Procedure and Handlers
i. Exit
20. String class ‗s methods and property
21. Char class‘s methods
22. Other special functions
23. Windows Form
a. Modal/Modeless
b. Share data from on Form to other Form
c. SDI/MDI
d. MDI form with MenuStrip control
e. Context Menu
24. Exercise 2
25. Exception handling
a. Types of Errors
b. Types of exception handling
c. Structured exception
d. Debugging Techniques
26. COM and DCOM
2
Chapter -1
Event-Driven Model
C language follows the concept of procedural programming language.
Execution starts with the first line of code and follows a predefined path through
the application, calling procedures as needed.
For example , Vedika and Yash decided to play computer game called Car racing,
Vedika starts the game , she takes right turn then left turn then….. And finally
wins the game. Now about Yash, he starts the game; first he takes reverse and
meets accident and losses the game.
What is the main moral? The goal of Vedika and Yash are same to play Car racing
game, but sequence is different. Yash meets the accident, but Vedika doesn‘t. We
are not sure for sequence.
The sequence of these events determines the sequence in which the code
executes, thus the path through the application's code differs each time the
program runs.
In daily routine we are using so many objects like TV, Ice-Cream, Bike, Car,
Mobile, Laptop etc.
For example, when we want to purchase Laptop then what we will ask to
shopkeeper? Cost of it, company, color, size, RAM, Hard-disk, Bluetooth etc...
This all are properties of Laptop. Basically properties include visible
attributes.
Why we like to go ADLABS Theater? Due to the facilities like sound system,
comforts of seats and environment. This all are the attributes of ADLABS.
3
Click Event
Events are reaction of any action. Suppose I will give one slap to my daughter
what will be the reaction of her? She will definitely start crying. That is the
reaction of my action.
In above images example button Click of Login Form, Birthday party is the
reaction of happiness, Abhishek bachaan‘s reaction of angriness and final
example is the dog‘s reaction against your action of teasing.
Methods are nothing but function or procedure. Like filling air in tier,
walking, drive the car, push break in car etc. these all are methods.
Now we will see the form given below with its properties, events and methods.
Textbox_TextChanged TextBox.Clear()
Textbox Font
4
Visual Studio .NET
Visual Studio .NET is like MS Office.
MS Office is a package of different types of software. Each software has its own
purpose.
For developing any type of software in Visual Studio .NET we have to select
language.
Visual Studio .NET supports 20 languages for developing software. Some common
languages are Visual Basic .NET, Visual C++ .NET, Visual C# .NET, and Visual J#
.NET.
Suppose anybody tell us that I am programmer and working in .NET then we should
ask 2 questions to the programmer,
I think now we all are clear, that Visual Studio .NET is one kind of software. With the
help of Visual Studio .NET we can create sofwares with different programming
language.
Some common types of project that we can develop in Visual Studio .NET are as
below:
Features of .NET
5
Let‘s see, what makes .NET a wonderful platform for developing modern applications?
In C and C++ programs uses header files like ―stdio.h‖, ―iostream.h‖, etc.
Visual Studio .NET contains hundreds of classes and namespaces that provides
variety of functionality in your applications.
The garbage collector takes responsibility for free up unused objects for regular
intervals.
This means that if your friend has skills in C++, and you have skills in VB you both
can work in same application. You can write logic in C# and you can VB.NET.
The beauty of multi language support lies in the fact that even though the syntax of
each language is different, the basic environment of developing software is same.
ASP.NET is useful for developing dynamic and data base related web applications.
ASP.NET contains rich and faster development controls for web applications.
XML support
Visual Studio .NET supports for writing, manipulating and transforming XML
documents.
Deploying windows applications especially that used COM components were always
been a tedious task. Since .NET does not require any registration as such, much of
the deployment is simplified.
What is VB.net?
6
VB.NET is nothing but a programming language.
"Visual" part refers to the way used to create the GUI base applications.
Visual Basic .NET is the next generation of the Visual Basic language.
7
What is .NET Framework?
The .NET Framework is a service or platform for building, deploying, and running
applications.
The .NET Framework consists of 2 main parts: common language runtime and class
libraries
It provides an infrastructure for run programs and allows them to communicate with
other parts of the .NET framework.
Languages must agree on the meanings of these concepts before they can
integrate with one another.
8
CLS forms a subset of CTS. This implies that all the rules that apply to CTS apply
to CLS also.
1. Value types
2. Reference types
Value types
Reference types
Store a reference to the value's memory address, and are allocated on the heap.
What is an assembly?
An assembly is the primary building block of a .NET Framework application.
All managed types and resources are marked either as accessible only within
their implementation unit or as accessible by code outside that unit.
A shared assembly is one that can be referenced by more than one application.
9
In order to share an assembly, the assembly must be explicitly built for this
purpose by giving it a cryptographically strong name (referred to as a strong
name).
By contrast, a private assembly name need only be unique within the application
that uses it.
What is metadata?
Metadata stored within the Assembly.
A .NET language compiler will generate the metadata and store this in the
assembly.
On the .NET Platform programs are compiled into .NET PE (Portable Executable)
files.
The header section of every .NET PE file contains a special new section for
Metadata.
• Locate classes
• Load classes
• Generate native code
• Provide security
Same here, the .NET Framework are collection of classes or namespaces that can
be used to develop applications.
The class library consists of data classes, XML classes, Web Forms classes,
Windows Forms classes, Smart device classes, Input Output classes, etc.
What is Namespace?
As above, .NET Framework class library is collection of namespaces.
Namespace is a logical naming scheme for types that have related functionality.
Like my computer contain C:, D:, E: and F:. Each drive contains 1.txt file..
10
For example, my friend wants 1.txt file. So I will ask him which one file? C:‘s
1.txt , D: 1.txt , E:1.txt or F:1.txt?
The drives are logical partitions of hard-disk. C:,D:,E:,F: are used for unique
identification for particular file.
When the paymaster stands and calls out the names of people to receive their
salary, the GM Shyam Chawda won't be happy if he rushes to the table when the
paymaster calls out his name and the envelope contains the Tester Shyam
Chawda's salary only 10000.
To resolve the naming ambiguity, the Reliance Industry can simply define three
namespaces: Executive, General Manager and Tester. Now the three individuals
can be unambiguously referred to by their fully qualified names:
Executive.Shyam Chawda
GeneralManager.Shyam Chawda
Tester.Shyam Chawda
Above three posts Executive, General Manger and Tester are like namespace. They are
used for identifying Shyam Chawda differently.
Same like above Namespaces provide scope: Two classes have the same name but they
should reside in different namespace.
Common Namespaces
System
Contains fundamental classes and base classes
System.Data
Contains classes for the database connection.
System. IO
Contains classes for reading and writing data in file.
System. XML
Contains classes work with XML
System.Windows.Forms
Contains classes for Windows-based applications
System.Data
Include classes that make up ADO.NET
11
It then automatically free up the memory used by that object.
One of the advantages of CLR is automatic memory management that uses the
garbage collection mechanism.
The CLR‘s garbage collector GC manages the allocation and release of memory for
an application.
We do not have to write code to perform memory management tasks when you
develop managed applications.
12
Write down Managed execution process of .NET program
Program execution of VS.NET
Select compiler
Compile MSIL
MSIL toto
Native with code
Native the help of JIT
For vb.net select VBC, for C# select CSC same for all language wise select
compiler.
Converting your source code into MSIL and generates the metadata.
The CLR provides the environment that enables execution to take place and
provide other services,
Combined with metadata and the common type system, MSIL allows for true
cross-language integration.
What is JIT?
13
It stands for "just-in-time‖.
JIT does not compile whole program each time and every time. It compiles only
that portion of the program which functions are called that time.And suppose
Native code is already present then that data will not again compiled. If changes
are made then possible that it will again generates MSIL to Native.
Firstly any program compile by its own compiler then it will convert into MSIL
then with the help of JIT; MSIL compile into Native code but CLR does not convert
whole MSIL code to Native code on Load time of that application; instead of it
compiles the MSIL instructions as they are called.
Normal-JIT – It‘s like Econo-JIT. The methods are compiled the 1st time they are
stored in cache. When the same methods are called again the compiled code from
cache is used for execution.
14
What is AssemblyInfo.vb file?
An assembly is the basic building block of .NET application.
The AssemblyInfo.vb file contains information about the assembly, its version
number, dependencies, product, copyright, trademark, description etc.
The AssemblyInfo.vb file looks as follows:
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly: AssemblyTitle("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
What is ILDASM?
It‘s one kind of software. It is used to view basic information about the project.
It displays the MSIL code, namespaces, methods, fields, events, interfaces, etc.
To open go -> Microsoft Visual Studio 2005 -> Visual Studio Tools -> Visual Studio 2005
Command Prompt -> Type ildasm or ildasm.exe
15
Select any Visual Studio
project -> bin ->debug
folder -> select .exe file
program and the actual Intermediate Language code. For it double click on MANIFEST we
will able to view details of assembly.
Now click
16
on project name it will display namespace, class, interface, enum , method ,event,
property, etc.
Symbol Meaning
More info .
Namespace
Class
Interface
Enum
Method
Static method
Field
Static field
Event
Property
Manifest or a class info item
The above image displays description of clsEmp like methods , properties, fields etc
17
What is IDE?
Any software is identified by its IDE.
Compare Notepad and Microsoft Word, which one is best for letters and
documents? Your answer is obvious Microsoft Word. But why? Because the
facilites. Facilites like menu bar, formatting option, toolbar, layout options, chart-
drawing options, etc. These all are parts of IDE.
Menubar
Toolbar Solution Explorer
Design View
Context Menu
Screen of VS.NET
18
Menu Bar
Very common for any Software. Contains options like File, Edit, View, Project,
Build and Help menus.
Context Menus
To open a context menu, select any object and click the right mouse button.
The specific list of shortcuts available from context menus depends on the part of
the environment where you click the right mouse button.
Toolbars
Provide quick access to commonly used commands like save, undo, comment,
cut, copy, paste, run etc.
We can add other toolbars from view menu or right click on toolbar itself.
Like Window explorer will shows us windows file, same for Solution explorer it will
show us each items of our project files, forms, classes, namespaces, database
etc. that we include in our solution
We can use this window to view and change the design-time properties.
19
Immediate, Locals, and Watch Windows
To view it select View menu -> Other Windows -> Task List.
We can add User Tasks, which are notes about work to be done. A task can be
anything like comments, reminders, URL, etc.
Display Task Comments that link to lines in your code where work must be done.
We can execute both menu commands and commands that do not appear on any
menu.
20
Our first program in Vb.net
Shortcut to open Visual Studio.net is
DEVENV
Go in the run window and type it.
Devenv stands for Developer
Environment.
Second way
Go Start windows ->Programs -> Microsoft Visual Studio 2005 -> Microsoft Visual Studio
2005
Third way
From short cut of desktop
When Visual Studio.net is open then go -> File Menu ->New Project ->
Windows application
Our first program is display message on the click of button
1. Open Visual Studio. NET
2. Give proper name to your project, usually I prefer sln prefix for project sln stands
for Solution. Means if we are going to create project for Student then give
slnStudent to your project. We can also use prj prefix it stands for Project.
21
3. Now add the controls. Toolbox contains various controls. It found on the
left of the screen.
We can add any control on the form by Drag and Drop control from toolbox or
double click on control.
Add button control to our form1.
4. Now double click on the button1 control, below coding window will
appear.
22
5. Save the Project
6. Test and Debug your application.
23
Exercise 1:
Q1 Answer the following:
CLR
CTS
MSIL
IL
CIL
JIT
CLS
VS.NET
VB.NET
IDE
FCL
GC
.NET Framework
CLR
CTS
CLS
MSIL
Managed code and Managed data
Assembly
Metadata
Namespace
Garbage collection
JIT
Q.4 Do as directed:
24
f. The major components of .NET framework are __________ and ________.
g. Solution is collection of _______________.
h. Imports keyword is used to imports _________________.
i. Extension of Solution file is __________ and Project file is _______.
j. VB.NET is an example of Software. (True/False)
k. Compiler of Vb.net is _____________.
l. VS.NET is an example of programming language. (True/False)
25
Chapter-2
Variable
A variable is something that is used in a program to store data in memory.
A variable has a name (the word you use to refer to the value the
variable contains) and a data type (which determines the kind of data
the variable can store).
Variable Declaration
Using Dim statement we can declare variable.
Example:
Data type
The data type of a programming element refers to what kind of data it can hold
and how that data is stored.
Short
It occupies 2 bytes.
26
Prefix we can use ‗sht‘ and store only whole number
Integer
It occupies 4 bytes.
Long
It occupies 8 bytes.
Single
It occupies 4 bytes.
Prefix we can use ‗int‘ and store whole and fractional both
Double
It occupies 8 bytes.
Prefix we can use ‗dbl‘ and store whole and fractional both
Decimal
It occupies 16 bytes.
27
The range of it 0 to +/-79,228,162,514,264,337,593,543,950,335 with no
decimal point; 0 to +/-7.9228162514264337593543950335 with 28 places to the
right of the decimal; smallest nonzero number is +/-
0.0000000000000000000000000001 (+/-1E-28).
Prefix we can use ‗dec‘ and store whole and fractional both
Char
It occupies 2 bytes.
String
It occupies 2 bytes.
Boolean
It occupies 2 bytes.
Byte
It occupies 1 byte.
28
Prefix we can use ‗byt‘
Usually Byte data type is used to access binary files, image and sound files etc.
Date
It occupies 8 bytes.
Object
It occupies 4 bytes.
Example:
Dim objTemp As Object
objTemp = 5
objTemp = "Ram"
objTemp = #10/17/2008#
Use Object at compile time when you do not know what data type the variable
might point to.
Whatever data type it refers to, an Object variable does not contain the data
value itself, but rather a pointer to the value.
The Object data type is slower than using explicit data types. But why?
When we create any variable it stores data into that variable only.
5
For example, if we create Dim A As Integer=5
Xyz
In memory; box is created the name of the box is A, the address of that box is
Xyz and it contains value 5
So when we get or set the value of variable A, it directly deals with that memory
box only.
29
In memory, 2 boxes are created 1st one is A it stores the address of 2nd box which
contains value 5
5
Xyz
Object data type isAbc
slower than other data type Xyz.It takes more time to fetch
and store the data, because it first has to point other memory block and then
perform operation.
It always uses four bytes in computer memory, but this does not include the
storage for the data representing the value of the variable.
The Object data type requires more memory than other data types.
30
Variable Initialization
In VB.NET each variable contains default value depends on its data type.
Example: Dim no As Integer
The default value of no variable is 0
The default initialization values are as follows:
Nothing for all reference types like Object, String, and Arrays etc.
Example: Take user input in the Textbox control and print in another textbox
control.
Step 2: Change the name and text property of Label, Textbox, Button and Form control
Set Form controls‘ Name property when we add new form from solution explorer. The
form name like ‗frmAdd‘, ‗frmStuInfo‘ etc.We can use ‗frm‘ as a prefix of the Form
control and after adding change the Text property so, Title of the form can be displayed
properly.
Set Label control‘s Name property like lblName and lblAns. ‗lbl‘ is the prefix of Label
control and Text property like Name and Ans.
31
Set Textbox control‘s Name property like to txtName and txtAns. ‗txt‘ is the prefix of
Textbox control.
Set Button control‘s Name property like btnAns or cmdAns. We can use either ‗btn‘ or
‗cmd‘ as prefix of Button control.
If we do not give proper prefix to that control how can we know the type of the control,
for example if our form has 50 Textboxes and 50 Labels and we assign the name like
‗eena,meena,dika, etc.‘ then is it easy for programmer to identify type of the control or
easy to identify which control we are working? No.
Coding Window
txtAns.Text = txtName.Text
End Sub
Form
When we click on btnAns control, that time event will raise and task is transfer data from
one control to another.
Example:
btnAns
32
lblAns
But answer is wrong. Why? Remember that Textbox always return String value.
Coding Window
In VB.NET + operator can work for Addition and Concatenation both, here + operator
work as a Concatenation operator. It concats 2 string value.
Function name
Argument Return type
Coding Window
We need to convert both string value in the Intger as above and now check the program.
33
Type Conversion Function
Type conversion is used for convert one data type to another.
An implicit conversion does not require any special syntax in the source code.
Dim A As Integer
Dim B As Double
A = 4499
B=A
As above, The VB.NET will convert smaller data type to larger (Integer < Double)
automatically is also called as Narrowing to Widening conversion.
The following table shows the available conversion functions used for explicit
conversion.
Example:
34
CTYPE Function
Example:
no2 = 66.77
MsgBox (no1)
With Boxing and unboxing one can link between value-types and reference-types by
allowing any value of a value-type to be converted to and from type object.
Boxing
Unboxing
Example
Dim no As Integer=10
35
Type Checking Functions
VB.NET provides number of data verification or data type checking functions as below:
IsDate
IsNothing
IsNumeric
IsDBNull
IsArray
IsDate
Example:
IsNothing
Returns True if the Object variable that currently has no assigned value;
otherwise, it returns False.
Example:
IsNumeric
36
Example:
objTemp = "53"
bolAns = IsNumeric(objTemp) ' Returns True.
MsgBox(bolAns)
str = "459.95"
bolAns = IsNumeric(str) ' Returns True.
MsgBox(bolAns)
IsDBNull
IsDBNull returns True if the value evaluates to the DBNull type; otherwise,
returns False.
Example:
objTemp = "Karna"
bolAns = IsDBNull(objTemp) ' Returns False.
MsgBox(bolAns)
objTemp = System.DBNull.Value
bolAns = IsDBNull(objTemp) ' Returns True.
MsgBox(bolAns)
37
Option Explicit and Option Strict
Option Explicit
Value: On / Off
Default: On
If used, the Option Explicit statement must appear in a file before any
statements.
We can reduce the possible errors that result from misspelled variable names.
If we don't declare variable before it used, all undeclared variables are of Object
type.
Example
Now,
Option Strict
Value: On / Off
Default: Off
If used, the Option Explicit statement must appear in a file before any
statements.
38
Some time data loss can occur when the value of one data type is converted to a
data type with less precision or smaller capacity.
Example
Now,
Run project
Coding Window
We can set both options by Tools Menu -> Option -> Projects and Solutions
39
Operators
An operator is a symbol or character.
Example:
Dim Ans As Integer
Ans=2+5
Unary Operators
Used with a single operand.
Example:
Ans=-10
Binary Operators
Used with a two operands.
Example:
Ans=10/5
Category of operators
Arithmetic ^, –, *, /, \, Mod, +, =
Concatenation &, +
40
Arithmetic Operators
* Multiplication
+ Addition
- Subtraction
/ Regular division
Example:
Example:
Example:
Example:
Dim no1 As Integer = 5
Dim no2 As Integer = 3
Dim ans As Integer
41
Example: Create simple calculator using 2 textboxes and 1 label for answer.
Take 5 buttons for perform +,-,X,\ and Clear the values.
End Sub
End Sub
End Sub
lblAns.Text = ""
txtNo1.Clear()
txtNo2.Clear()
End Sub
Concatenation Operators
Example:
MsgBox(str)
42
MsgBox(str)
We can write either Str &=‖ I love my India‖ (shortHand) or Str =Str & ‖ I love
my India‖
Example:
Assignment Operators
^=, *=, /=, \=, +=, -=, &= are also known as Shorthand operators.
Example:
Dim No As Integer
No -= 2 ‗ -=
MsgBox(No)
Relational/Comparison Operators
They perform some comparison between two operands and return a Boolean value.
= Equality
43
Example:
Dim no As Integer
TypeOf...Is
The TypeOf...Is operator is checked first parameter and with the type as its
second parameter.
Example:
End If
IS
The Is operator determines whether two object reference variables refer to the
same object instance.
Example:
44
Like
The Like operator can work only with operands of type String and
Character.
Example:
MsgBox(bolAns)
MsgBox(bolAns)
MsgBox(bolAns)
Example:
MsgBox(bolAns)
Example:
MsgBox(bolAns)
Example:
45
bolAns = "R" Like "[!A-C]" ‗Returns True , means not between A,B,C
MsgBox(bolAns)
Example:
MsgBox(bolAns)
Example:
MsgBox(bolAns)
Bitwise/Logical Operators
The logical operators compare Boolean expressions and return a Boolean result.
And
Example:
no1 = 10
no2 = 20
46
Or
If one of the conditions is true then return true and follows the logic.
Example:
no1 = 10
no2 = 20
AndAlso and OrElse are like And and Or except that they will "short circuit".
AndAlso
If first one condition is false then the output is obvious False only, so why should
waste time to check second condition.
It Saves time.
AndAlso = If first one condition is True then and then check second one condition.
AndAlso = And+Also
Example:
no1 = 10
no2 = 20
In above example, first condition is False so AndAlso operator doesn‘t waste time
to check second one.
47
OrElse
If first one condition is True then the output is obvious True only, so why should
waste time to check second condition. Whether second condition is True or False
output of OR is True only.
It Saves time.
OrElse = If first one condition is True then and then don‘t check second one
condition. If first one condition is False then and then check second one condition.
OrElse = Or+Else
Example:
no1 = 10
no2 = 20
In above example, first condition is True so OrElse operator doesn‘t waste time to
check second one.
Xor
Example:
48
Dim c As Integer = 2
Not
Performs a Boolean Not operation on the bits in the operand. This is a unary
operator.
Example:
Dim a As Integer = 5
Miscellaneous Operators
GetType
Syntax: GetType(typename)
Example
Dim a As Integer = 5
MsgBox(a.GetType().ToString)
MsgBox(btn.GetType().ToString)
49
Write down in memory.
Example:
MsgBox(strName)
Shared variable are global for all the events and procedures.
Follows the Prefix for variables and controls it‘s a habit of a good programmer.
Run your project. After this, remove the above line and write below the line and
run your project and compare output.
50
We can add multiple forms in a project, so don‘t create New project for each and every
time.
We want to run other form from our project when we press F5 then it makes them as a
Startup form as given below:
51
What is comment?
Comments are optional part of coding.
We add comments in our program to make clear particular concepts. Like why we
take this variable? What is the use of this Procedure? Programmer of this form.
Date when we create this form. Etc.
Toolbar
First select lines which we want to comment and then Select Comment icon. We can do
multiline comment using this option.
Coding Window
52
What is design and run time?
Design time
The time, during which you build an application in the development environment
by adding controls, setting control or form properties, and so on.
Property Window
Run time
The time, during which code is running. During run time, you can't edit the code
txtPwd.PasswordChar=‖*‖
53
Control Structure
It‘s deciding the flow of program.
The condition is evaluated runtime and depending on the result of condition, the
block of code will execute.
1. If...Then..Else
2. Select Case
If…Then…Else
There are cases when we would like to execute some logic when a condition is
TRUE, and some other logic when the condition is FALSE.
If the contition is TRUE then the control goes to between IF and Else block , that
is the program will execute the code between IF and ELSE statements.
If the contition is FALSE then the control goes to between ELSE and END IF block
, that is the program will execute the code between ELSE and END IF statements.
We can write only If block. The ElseIf and Else clauses are both optional.
Syntax:
If condition Then
Logic..
ElseIf condition-n Then
Logic…
Else
Logic…
End If
54
Example: Single If block
If IsNumeric(txtNo.Text) Then
End If
Else
End If Form
End Sub
no1 = txtNo1.Text
no2 = txtNo2.Text
Example:
55
Else
Logic…
End If
Select….Case
When you are comparing the same expression to several different values, we can
use the Select...Case statements as an alternative to the If...Then...Else
statements.
It‘s possible in If..Then..Else block to satisfy multiple If and ElseIf condtions then
multiple logic will run , but If multiple Case statements are True, only the
statements belonging to the first true Case statement are executed.
If any Case statement is satisfied logic will run that only and then control will
come out of Select block. This one will not happen with If…Then..Else block.
We can add any number of Case statements, and we can include or remove a
Case Else statement.
If no one Case statement is satisfied then Case Else clause‘s logic will run.
Case Else is an optional staement. If used, the Case Else must be the last Case
clause. Otherwise it will execute all the time.
We can also use Is keyword. The Is keyword is used with any comparison
operators.
Syntax:
Case expressionlist-n
Logic ...
Case Else
Logic ...
End Select
Example:
56
Private Sub btnAns_Click()
Case 2
lblAns.Text = "You are infant"
Case 3, 4
lblAns.Text = "You are in Sr. or Gr. KG" Form
Case 5 To 12
lblAns.Text = "You are in Primary Section"
Case 12 To 15
lblAns.Text = "You are in Secondary Section"
Case Is < 18
lblAns.Text = "You are in Higher Secondary Section"
Case Else
lblAns.Text = "No idea"
End Select
End Sub
57
Loops
Looping structures are used when a group of statements is to be executed repeatedly,
until a condition is TRUE or until a condition is FALSE.
The following illustration shows a loop structure that runs a set of statements until a
condition becomes true.
VB.NET supports the following loop structures.
1. For Next
2. Do Loop
3. While End While
4. For each Next
For… Next
It‘s most commonly and most popular loop used in any programming language.
Syntax:
Examples:
Here counter variable is initialized when the loop starts and runs upto the end
values. We can not use i++ like in C (for i=0;i<10;i++) over here.
58
The step value can be positive to increment and negative to decrement the
counter.
Dim i As Integer
For i = 0 To 10
txtAns.Text = i
Next
Form
End Sub
But answer is wrong why? The value of txtAns.Text is overwrite everytime upto loop
will run.
We should use ―&‖ operator to concat the value.Write down below coding and then run
our project again.
Dim i As Integer
For i = 0 To 10
Next Form
End Sub
Space function
Both are used for New line like ‗\n‘ effect in C or C++.
59
Example: Print 1 to 10 in Textbox using For..Loop vertically.
To print vertically we need to set the property of TextBox is Multiline =True and
then increase the Height of textbox by stretching it. And write down below coding
Dim i As Integer
For i = 0 To 10
Next
While loop
While loop keeps executing until the condition against which it tests remain true.
The While statement always checks the condition before it begins the loop.
Syntax
While condition
Logic..
End While
Dim no As Integer = 5
While no > 0
Msgbox(no)
no = no – 1
End While
60
Do… Loop
Syntax
-or-
Do
Logic..,
Loop { While | Until } condition
While
Repeat the loop until condition is FALSE.
Until
Repeat the loop until condition is TRUE.
61
For Each…Next
The For Each...Next loop is similar to the For...Next loop, but it executes the
statement block for each element in a collection or arrat.
We will learn more about collection and arrays in the later topics.
Syntax
noArr(0) = 11
noArr(1) = 22
noArr(2) = 33
MsgBox(temp)
Next
Next
MsgBox(cnt)
Form
End Sub
62
With…End With
Executes a series of statements making repeated reference to a single object.
To make this type of code more efficient and easier to read, we use this block.
The use of it do not require calling again and again the name of the object
With…End With allows us to set multiple properties and methods quickly and
easily.
Since the object is referenced only once, the code runs faster.
Syntax
Mobile.CompanyName=‖Nokia‖
Mobile.Prize=‖2500‖
Mobile.FM=‖No‖
Mobile.Series=‖N3310‖
The same code could be written using the With..End With statement as given below:
With Mobile
.CompanyName=‖Nokia‖
.Prize=‖2500‖
.FM=‖No‖
.Series=‖N3310‖
End With
With btnAns
.Text = "Click Me"
.ForeColor = Color.White
.BackColor = Color.Green
.Height = 50
.Width = 100
End With
63
Write down in memory.
To stop an endless loop, press ESC or CTRL+BREAK.
Me.Text means current form‘s caption. In short, after ―Me.‖ We can set properties
of the form.
Me.Text=”Calc” or Text=”Calc” both are same. Both will change the title of
the form.
Me.controls is the collection of the current forms which stroes the information of
the controls lying on the form.
Use CTRL+SPACE to save your time to coding. Like type txt and then press
CTRL+SPACE, All the controls starts from txt will display.
The files and their extensions which are created as part of the Windows
Application Project and their meaning are summarized below:
64
Msgbox ,MessageBox.show and Inputbox.
The objective of MsgBox is to produce a pop-up message box , prompt the user
and returns an integer indicating which button the user clicked
MsgBox
Syntax:
ans=MsgBox(Prompt, Button + Icon Style, Title)
Promput argument will display the message in the message box.The Style Value will
determine what type of command buttons appear on the message box.The Title
argument will display the title of the message box.
Prompt is the compulosary argument of it, Style and Title arguments are optional.
Example:
MsgBox("Hai")
Example:
Constant Description
OKOnly Display OK button only.
OKCancel Display OK and Cancel buttons.
AbortRetryIgnore Display Abort, Retry, and Ignore buttons.
YesNoCancel Display Yes, No, and Cancel buttons.
YesNo Display Yes and No buttons.
RetryCancel Display Retry and Cancel buttons.
Critical Display Critical Message icon.
Question Display Warning Query icon.
Exclamation Display Warning Message icon.
Information Display Information Message icon.
DefaultButton1 First button is default.
DefaultButton2 Second button is default.
DefaultButton3 Third button is default.
65
Msgbox returns an integer value. The value is determined by the type of buttons being
clicked by the users. The list of button below and the return value of it.
Value Button
1 vbOk
2 vbCancel
3 vbAbort
4 vbRetry
5 vbIgnore
6 vbYes
7 vbNo
Example:
MessageBox.Show
Show method has more arguments then MsgBox function.It contains separate
arguments for icon and button.
Syntax:
Example:
66
InputBox
An InputBox function will display a prompt box where the user can enter a value
or a message in the form of text.
Instead of taking Textbox on the form we can get the user value using InputBox.
The Inputbox function with return a value. We need to declare the data type for
values to be accepted in the Inputbox.
Syntax:
The prompt argument will displayed message as a question asked. The title argument is
the title of the Input Box. The default text argument appears in the input field where
users can use it as his intended input or he may change to the message he wish to key
in and x-position and y-position are the position or the coordinate of the input box.
Example: Accept the name from InputBox and display name in the messagebox.
MsgBox(ans, , "Ans")
Example: Take 2 values from the user and find the maximum between them.
67
Procedure
A procedure is a set of one or more prgrom statements that can be run or call by
referring to the procedure name.
Due to Procedure the applicaton is easier to debug and easier to find error.
Modular Coding
There are 2 approaches for doing modular coding in VB.net
If your procedure does not return any value then it should be implemented as a sub
procedure else function.
Procedure1 starts
Logic...
Procedure2 (para1, para2)
Logic…
Procedure1 ends
Logic..
Procedure1 ends
68
Sub Procedures
Sub procedure may or may not have arguments. Arguments are not
compulsory.
ByVal is by default argument type. So, do not worry to type it. It will
automatically appear if we set parameter in the Sub procedure.
Syntax:
Logic…
End Sub
Example: Create Sub Procedure when user click on button it will call
Coding Window
We can call sub procedure using Call keyword or without Call keyword.
When we declare procedure it will automatically appear in the context menu as given
below.
End Sub
69
Coding Window
Now go to btnAns_click event and type Call Hai and we can see the magic as above
image will display.
Calling syntax:
Logic.. Logic..
70
Function
Because function can return the value so, commonly we can call function using:
somvariable=functioname(arguments)
Function runs the logic and returns the value in that variable.
Syntax
Logic….
[Return value]
End Function
Example: Create Square function which takes one argument and returns square
of that argument.
Return No * No
End Function
Form
Coding Window
Our Function
lblAns.Text = Square(txtNo.Text)
or
lblAns.Text = Square(5)
Return a+b
End Sub
If a mod 2 =0 then
Return True
Else
Return False
End if
End Sub
72
Optional Argument
We can specify procedure argument as an optional.
Optional means not to pass argument compulsury when the procedure is called.
They are indicated by the Optional keyword in the procedure default value else if
we pass then default value is overwritten.
If we do not pass the value of optional argument then it will take its default
Rember that if we make one argument optional, all the following arguments must
be optional.
Syntax
End Sub
End Function
Example: Create Add subprocedure which contains one of the argument is optional.
MsgBox(no1 + no2)
End Sub
Compulsory argument
Coding Window
73
Calling Syntax:
Call add(5)
Or
Call add(5,10)
Example: Create PrintData function which takes 2 arguments char and integer
both are optional.
Dim i As Integer
For i = 0 To no
txtName.Text &= ch & vbCrLf
Next
End Sub
Calling syntax:
Return a * b * c
End Function
Error will display. Why? Because the concept of Optional argument is that if we make
one argument optional, all the following arguments must be optional.
74
Function Overloading
Overloading means reusing a name.
VB.NET follows OOPs concept and function overloading it‘s the implementation of
the “Polymorphism” concept of the OOP.
VB.NET allows specification of more than one function of the same name in the
same scope.
When we declare more than one procedure with the same name but number
arguments may be differing, types of arguments may be differing or sequence of
those arguments may be differing.
Do not use the concept of Optional argument and Function overloading in same
program with the same name. Sometime it will create lots of confusion and will
generate error.
Example: Create 4 add() functions that show the demo of function overloading.
Sub add()
Logic..
End Sub
Logic..
End Sub
Logic..
End Sub
Sub add(ByVal no1 As Integer, ByVal no2 As Integer, ByVal no3 As Integer)
Logic..
End Sub
75
*
Now we are going to call it.
All add() procedures are grouped and we declare 4 subprocedures and we are currently
in 1 so that the reason it will display 1 of 4 if wants second then click on
76
Pass by Val /Pass by Ref
There are two ways to pass arguments: ByVal and ByRef.
ByVal refers that you are passing a copy of a variable to procedure. We can make
changes to the copy and the original will not be altered. The variable itself
will not change within the procedure or function.
In ByRef both the variable and the argument refer to the same memory location
hence the ByRef keyword.
We can not run more than one value from any function using Return
keyword.
Bascially we can return more then one value from functions using ByRef. It‘s not
exactly returns the value but performs like that only.
Dim x, y As Integer
x = txtNo1.Text
y = txtNo2.Text
Swap(x, y)
txtAns1.Text = x
txtAns2.Text = y
End Sub
Form
Sub Swap(ByVal a As Integer, ByVal b As Integer)
temp = a
a=b
b = temp
End Sub
77
Answer is wrong due to ByVal, the changes are made in only subprocedure but not
reflect to passed variable.Now make changes as below and run again program.
End Sub
Form
78
Common mechanism for Passing Argument
Usually in any programming language when we call a Sub or Function procedure,
we pass arguments by position — that is, in the order in which they appear in the
procedure's definition.
Example: By Position
Logic…
End Sub
Mix mode of both above. If we supply arguments both by position and by name,
the positional arguments must all come first.
Example:
Sub Addimision(ByVal name As String, ByVal total As Single, ByVal fdate As Date)
End Sub
79
Event Procedure and Handlers
Event procedures are bound with controls.
There are numbers of event related with one control but depends on our
reqirement we are using it.
We know the number of events related with the control as given below:
Coding Window
Event handler
When the event is raised, the logic within the event handler is executed.
The event subroutine arguments sender and e and the Handles clause
The Handles clause attached the control‘s event. Means which controls‘ event
handle this logic.
Example:
Logic…
Logic…
End Sub
80
Sender
The “sender” provides a reference to the object that raised the event.It gives
information of control tha is responsible to generate this event.
Example: Take 3 textboxes and one command button, assign button name property to
btnAns
End Sub
Example:
81
Example: When user closes the form ask to the user that do you want to close
the form if user presses yes then close it otherwise not.
End Sub
We can also use the same event handler to handle the same event for different
controls.
82
End If
End Sub
Coding Window
Form
First step is to design the form properly and give proper naming convention to each
control.
Second step is to click on btn0 and go at the end of the event handler as above image
and using comma add the all button‘s click event.
End Sub
no1 = txtAns.Text
txtAns.Clear()
op = sender.text
End Sub
83
If op = "+" Then
txtAns.Text = no1 + Val(txtAns.Text)
ElseIf op = "-" Then
txtAns.Text = no1 - txtAns.Text
ElseIf op = "X" Then
txtAns.Text = no1 * txtAns.Text
ElseIf op = "/" Then
txtAns.Text = no1 / txtAns.Text
End If
End Sub
txtAns.Clear()
End Sub
End Class
84
Exit
The Exit statement stops execution and jump to that part of the block.
The Exit statement has a different form for each type of block in which it can be used, as
listed here:
Staement Block
Exit Do In Do Loop
Exit For In For Loop
Exit Function In Function
Exit Property In Property
Exit Sub In Sub Procedure
Exit Try In Try…Catch..Throw
Dim i, no As Integer
Dim flag As Boolean
no = txtNo1.Text
For i = 2 To no - 1
If no Mod i = 0 Then
flag = True
Exit For ‘if ones number mod I is 0 then there is no need to check for prime
End If
Next
End Sub
85
String Class’s Properties and Method.
Length
Len() is function also. We can use any of this 2 options to check length of the
string.
Example:
Functions
Compare
Example:
Concat
Combined 2 strings. Places them one after the other and forms a new string.
Example:
Copy
86
Copy string. From source to destination.
Instead of this we can use directly = operator like a=b means copy from b to a
also.
Example:
str2 = String.Copy(str1)
MsgBox(str2)
Output:
Equals
Example:
MsgBox(String.Equals("ABC", "ABC"))
Output:
True
TRIM
Removes starting and ending spaces from the string and ending of the string by
default.
We can also pass parameter and remove particular character from starting and
ending of the string.
Example:
MsgBox(str.Length)
Example:
MsgBox(str.Length)
str4 = str.Trim("#")
87
MsgBox(str4)
MsgBox(str4.Length)
EndsWith
Checks whether the end of this instance matches the specified String.
Example:
str = "Zubeidaa"
If str.EndsWith("a") Then
End If
Output:
Yes
StartsWith
Indexof
Example:
placeNo = str.IndexOf("E")
Output:
88
7,20
Example:
Str = "I AM FROM GONDAL SITUATED IN SAURASHTRA"
Str = str.ToLower()
str = str.ToUpper()
Insert
Example:
str = "KABHI ALVIDAA NA KEHNA"
MsgBox(str)
Output:
PadLeft, PadRight
Both are used for alignment purpose see the below example.
Example:
str = "I have $ 5000"
MsgBox(str)
Output:
000000000000I have $ 5000
89
Example:
str = "I have $ 5000"
MsgBox(str)
Output:
I have $ 5000000000000000
Remove
StartIndex means the position in this instance to begin deleting characters and
count means the number of characters to delete.
Example:
str = "Vatrapur Lake is good"
MsgBox(str)
Output:
Vatras good
Replace
Example:
str = "KABHI ALVIDAA NA KEHNA"
Output:
KBBHI BLVIDBB NB KEHNB
Example:
str = "KABHI ALVIDAA NA KEHNA"
Output:
BHABHI ALVIDAA NA KEHNA
90
Substring (IMP)
There are 2 types of arguments it. (Start Index) and (Start Index,Count).
StartIndex means from where to start and Count means upto how many
character
Example:
str = "123456789"
TextBox1.Text = str.Substring(5)
Output:
6789
Example:
str = "123456789abc"
TextBox1.Text = str.Substring(5, 3)
Output:
678
str = "123456789"
For i = 0 To Len(str) - 1
cntE = cntE + 1
Else
cntO = cntO + 1
End If
Next
MsgBox("Even are " & cntE & " Odd are " & cntO)
Str.subString(i,1) will give us single digit every time from starting to ending of the
string.
91
Char class’s method
As given below are the some of char class‘s methods:
For i = 0 To Len(str) - 1
ch = str.Substring(i, 1)
End Sub
92
Other inbuilt functions
Split
TextBox2.Text = TempA(0)
TextBox3.Text = TempA(1)
TextBox4.Text = TempA(2)
TextBox5.Text = TempA(3)
We can also give particular character from where we can split particular string
Split(txtName.Text, ",")
Join
IIf
Syntax:
IIf(Expression,Truepart,Falsepart)
93
Example:
MsgBox(strAns)
Mid
Syntax:
Mid(String,StartIndex,Length)
Example:
StrReverse
Syntax:
StrReverse(String)
Example:
ASC
Syntax:
94
Asc(char) or Asc(string)
Example:
CHR
Returns return the character associated for the input ASCII number.
Syntax:
Chr(number)
Example:
Shell
Syntax:
95
Example: Open calculator and notepad and send some keys
End Sub
SendKeys.Send("22")
SendKeys.Send("*")
SendKeys.Send("44")
SendKeys.Send("=")
End Sub
SendKeys
96
Date-Time Function
Dim dt As Date
dt = #12/21/1982# 'MM/DD/YYYY'
Return a date
Return Time
Format Function
Example:
97
Note down the meaning of M,MM,MMMM,d,dd,dd,yy,yyy,yyy,hh,mm,ss,tt
Math Function
98
Windows Forms
Right now in this book we are learning to create desktop base application.
Desktop base application is nothing but software, this software is made up of one
or more forms, and the forms are what users see.
Example:
What ATM machine is display is a form, the main one form is called MDI form and which
forms we get from option of that MDI, and those are called Child form of MDI.
Coding Window
Form
99
Some properties of the Form, we can use this property design or runtime both.
Name Gets or sets the name of the form. We should set proper
name of the form.
Opacity Gets or sets the opacity level of the form.(Intersting)
ShowInTaskbar Gets or sets whether the form is displayed in the Windows
taskbar. True or False
StartPosition Gets or sets the starting position of the form at run time.
There are 5 options as below:
CenterParent , CenterScreen , Manual
,WindowsDefaultBounds ,
WindowsDefaultLocation
Text Gets or sets the title of the form.
WindowState In which sate we want to open the form. There are 3 options
Normal, Maximize and Minmize. Gets or sets this.
Exmaple:
Dim no As Integer
100
msgbox(no) ‗Here we gets or say fetch the value of variable ―no‖
Readonly
Writeonly
Read and Write
End Sub
txtName.Clear()
txtPassword.Clear()
End Sub
101
Example: Opacity property it is related with transparency.
Some events of the Form are Load, Closing, Mouse down etc.
102
Modal / Modeless
Forms and dialog boxes are either modal or modeless.
A modal form requires the user to supply information or cancel or hide the dialog
box, before allowing the application to continue.
Modal dialog does not allow its parent window unless it is colosed.
A modeless form allows the user to supply information and return to the previous
task without closing the dialog box.
Example for Model form is Save, Save As Dialog in MS-Excel While it is opening
we can't do any thing in the application until we close that window.
Example for Modeless form is Find, Replace dialogs. We can use Find Dialog,
same time you can also work in that word application.
MessageBox and InputBox are a modal form. Check it practically to switch over
parent form. We can listen Beep. We can not switch over to parent form until we
close that dialog box.
Modeless forms we can jump or shift the focus between the form and another
form without having to close the initial form. Parallely we can work with
multiple forms.
We can continue to work elsewhere in any application while the form is displayed.
Modeless forms are difficult to manage, because users can access them in an
unpredictable order.
Now let see how to make or how to open form as modal and then modeless
Output
103
Private Sub btnName_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnName.Click
frm.ShowDialog()
End Sub
For open our form as modal we have to use first create the object of the existing
form and call ShowDialog() method and for modeles we have to call Show()
method.
Output
frm.Show()
End Sub
frm.Show()
End Sub
104
Share the data from one Windows form to other Windows form.
There are 2 ways to share the data as below:
1. Using FormName.ControlName
Form
lblName, lblSal
Form
Output
frm.lblName.Text = txtName.Text
frm.lblSal.Text = txtSal.Text * 12
frm.Show()
End Sub
105
Example: Share data of the form using Public variable
Output
lblName.Text = name
lblSal.Text = sal * 12
End Sub
End Class
And below coding written in the First form ,from where we jump
frm.name = txtName.Text
frm.sal = txtSal.Text
frm.Show()
End Sub
106
SDI/MDI
There are two main styles of user interface:
In WordPad, only a single document may be open; we must close one document
in order to open another.
MDI
When we minimize Excel, all of the document windows are minimized as well;
only the parent window's icon appears in the task bar.
107
Creating MDI Form
Add menu control in your form and give mnu prefix to menu control.
108
Double click the control to add one to your form. When you do, you'll notice two things.
At the top of your form, you'll see this:
Click inside the blue "Type Here" area, and the menu changes to this:
Property Window
109
Set the child form‟s properties like
StartPosition = CenterParent
FormBorderStyle=FixedSingle
MaximizeBox = False
ShowInTasbar=False
Form
End Sub
End Sub
End
End Sub
Form
Property Window
110
Context Menu
Context menu is also known as contextual, shortcut, and popup or pop-up menu.
In any windows application when we right click the mouse we get a menu which
might display some shortcuts from the Edit Menu, for example, cut, copy, paste,
paste special and so on.
All these menu items which are available when you right-
click are called Context Menus.
Drag and Drop Context Menu Strip control to the textbox control.
Toolbar
When you do, you'll notice two things. At the top of your form, you'll see this:
111
the Context men‘s item:
End Sub
Output
112
Exercise 2
Q.1 Answer the following question:
Q.2 Compare
Q.4 Write down program using proper controls like button, textbox, label etc.
1. Enter your name in textbox and display on label control on button click.
2. Take 2 textbox controls. Enter name in one textbox and surname in second
textbox. Now concat both in the label control on button click.
3. Create simple calculator with +,-, X, / buttons.
4. Give demo of each operator.
5. Enter year then detect the year is whether leap year or not using If..Then..Else.
6. Enter number in the inputbox and display that number is even or odd using
If..Then..Else
7. Take value from the user using inputbox and display that number is negative or
positive using If..Then..Else
8. Enter student‘s marks in 3 different textboxes and add them on button click and
then check if marks between 0-50 then give message fail, 50 –100 then give
message pass class, 100-150 second class, 150-200 then give message first class
using If..Then..Else
9. Recreate above 5,6,7,8 program using Select..case.
10. Find entered Year in Textbox is Leap year or not.
11. Find maximum between 3 textboxes and display answer in label.
12. Create a Table of entered no in Textbox and display answer in Textbox.
Like 5 X 1=5 to 5 X 10=50
114
13. Print Odd and Even number in different label like lblEven and lblOdd upto user
entered value in Textbox.(1 to N)
14. Print 11,22,33,44 upto user entered in textbox. (1 to N)
Like 1^1 =1
2^2 =4
15. Print Series
1
22
333
16. Factorial of given number in textbox.
17. Print A…Z in one textbox and Print Z..A in second textbox using For..loop.
18. Print only even numbers from 1 to 50 using Step keyword.
19. Change the forecolor of the textboxs to red and change the back color of the
buttons of the current form with just single click use the concept of For..each
loop.
20. Clear all the textbox value using For..each loop.
21. Give demo of With..End with.
22. Create a program for count total number of Vowels and Consonants in a Textbox.
23. Create a program for count total number of Uppercase and Lowercase characters
in a Textbox.
24. Show the moment of mouse and when we press button the textbox goes to that
location.
25. Create a Text box that accepts only uppercase.
26. Create a Text box which accepts only one time ―.‖ (Dot).
27. Create a group of Textboxes those accepts only numeric values. Write down
common logic of them(Sender).
28. Change color of the form on the right click and left click of the form.
29. ―India is India‖ find how many times India is in the string.
30. Do following program without using replace function.
115
33. Create User define Calci (using sender) with all the restrictions.
34. Give demo of Swapping of 2 variables.
35. Reverse string with upper case using Function procedure.
36. Write down the demo of Split function.
37. Create the program which shows the demo of function and sub both.
38. Using the concept of optional argument create a sub procedure that
we can call as below: (as discuss in the lecture)
Print()
Print(―S‖)
Print(―Jay‖,20)
116
Chapter-3
What is Error?
Error is something that is unexpected. Error can stop our program to run.
Types of Errors
1. Syntax errors
2. Run-time errors
3. Logical errors.
Syntax Errors
Syntax errors are those that appear while we write our code.
Visual Basic checks our code as we type and alerts if we made a mistake.
Syntax errors are easy to track down in VB.NET, because we get a blue line
pointing them out and fix them easily at the design time.
Example
cmdAdd.caption= "hello"
txtNo.tet=‖abc‖
Dim No Integer
Run-Time Errors
As their name suggests, these errors occur when the program is running.
For example, we might call system calculator using shell function. But if the path
is wrong, the application cannot open calculator and it stops running.
117
Example
Dividing a number by 0.
Logic Errors
Logic errors are those that appear at run time. They happen when your code
doesn‘t quite behave the way you thought it would.
Example
118
Exception handling
Exception handling is an in built mechanism in .NET framework to detect and
handle run time errors.
Run-time errors are an expensive fact of life both during development and
following the release of software to customers. Errors take time to find and time
to fix.
The .NET framework contains lots of standard exceptions. The exceptions are
anomalies that occur during the execution of a program. They can be because of
user, logic or system errors.
There are 2 ways to trap errors in VB.NET and gives proper message while error will
trap.
Syntax:
Try
'Code to be executed
Catch
'Error resolution code
Finally
„This code should execute, if exception occurred or not
End Catch
Try section: The block of code that may result in an exception and always gets
executed
Catch section: Attempts to act on an exception and is only executed when an exception
takes place
The Try block contains code where an error can occur and the Catch block
contains code to handle any error that does occur.
If any exception occurs inside the try block, the control transfers to the
appropriate catch block and later to the finally block.
119
We can have any number of Catch statements or none.
The code in the finally block will execute even if there is no Exceptions. That
means if you write a finally block , the code should execute after the execution of
try block or catch block
The Finally block should contain code which must always be executed, for
example to clean up resources like file handles or database connections.
The Try block can exist either with one or more Catch blocks or a Finally block or
with both catch and finally blocks.
Bascially Exception is a class. This class is the base class for all exceptions.
Catch ex As Exception will create a new 'ex' object of the class Exception.
The object of excpetion class includes a number of properties that help identify
the error.
In coding window write down just Try keyword then press enter, catch and end
try block will appear automatically.
Try
Catch ex As Exception
Finally
120
MsgBox("Hai in Finally", MsgBoxStyle.Information, "Demo")
End Try
End Sub
Output
ex.ToString() will give the user a large technical dump of the error that occurred like
the error description with path of the form in which error will raise, line of the error ,
event name etc.
ex.Message will give a more to the point error message. It displays only main moral of
the error.
Try
Catch ex As Exception
Finally
121
End Try
End Sub
Sometimes it‟s good to be precise about what kind of exception we are trying to
check for.
Try
Dim n, m, ans As Integer
n = txtNo1.Text
m = txtNo2.Text
ans = n / m
MsgBox("Ans = " & ans)
Catch ex As InvalidCastException
MsgBox("castProb", MsgBoxStyle.Exclamation, "Err")
Catch ex As ArgumentException
MsgBox("Argument", MsgBoxStyle.Exclamation, "Err")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
Finally Output
MsgBox("Hai in Finally", MsgBoxStyle.Information, "Demo")
End Try
OutOfMemoryException
NullReferenceException
InvalidCastException
ArrayTypeMismatchException
IndexOutOfRangeException
ArithmeticException
DevideByZeroException
OverFlowException
FileNotFoundException
DirectoryNotFoundException
122
Unstrucuterd exception handling
It‘s simple to use.
On Error Go To statement enables exception handling and specifies the location of the
exception-handling code.
Using the 'On Error GoTo <label>' statement directs execution to re-start at the
specified <label> in the event of an error.
Whenever an error occur 'On Error Resume Next' statement skip the statement and
continue execution on following statements
The 'On Error GoTo 0' statement removes from the current procedure and reset it to
Nothing.
n = txtNo1.Text
m = txtNo2.Text
ans = n / m
MsgBox("Ans = " & ans)
Help:
MsgBox("Some error", MsgBoxStyle.Critical, "error")
123
What is debugging?
It's an art of identifying our bugs in program.
In VB.NET we can debug out program with Breakpoint, Quick Watch and Add
Watch
BreakPoints
A breakpoint is a place to where VB.NET to stop program execution.
We add breakpoint by clicking in the margins. A brown circled then appears, indicating
where the code will break. The following two images show how to add breakpoint?
When we click in the margins, to the left of a line of code, a brown circle appears:
Run your program, and click the button. We will immediately returned to the coding
window. The place where we put the Breakpoint will now have a yellow arrow on top of
the brown circle. The brown line will now be yellow:
The yellow highlight indicates where in your code VB.NET is. To continue checking your
code, we can press either F10 or F11.
F11 key is step Into results in line-by-line stepping of current procedure and
subordinated procedures.
F10 key is step Over skips line-by-line stepping of current procedure, bypassing
subordinated procedures.
124
Quick Watch
We can right click of any object at runtime and select QuickWatch from the context
menu.
It displays the current value of the object or expression. It gives greater detail for any
selected object.
Runtime
Add Watch
We can right click of any object at runtime and select AddWatch from the context menu.
It always displays the value of selected object. While QuickWatch only ones.
Runtime
Watch Window
125
What is COM?
Component Object Model (COM) is a standard introduced by Microsoft.
It can be used in different environments even other than where it was created
COM objects are discrete components, each with a unique identity, which expose
interfaces that allow applications and other components to access their features.
They have built-in interprocess communications capability, and easily fit into an
object-oriented program design.
Each COM object operates as a server that receives and processes requests from
a client program, and generates responses
126
What is DCOM?
The full form of DCOM is Distributed Component Object Model.
It‘s a big brother of COM but the difference is that it process are spread across a
network.
DCOM communications also work between dissimilar computer hardware and OS.
DCOM uses the RPC mechanism to transparently send and receive information
between COM components (i.e., clients and servers) on the network.
COM vs DCOM
COM DCOM
127
What is Managed Code?
Managed Code is what Visual Basic .NET and C# compilers create.
Code that targets the common language runtime, the foundation of the .NET
Framework, is known as managed code
It compiles to Intermediate Language (IL), not to machine code that could run
directly on your computer. The IL is kept in a file called an assembly, along with
metadata that describes the classes, methods, and attributes (such as security
requirements) of the code you've created. This assembly is the one-stop-
shopping unit of deployment in the .NET world. You copy it to another server to
deploy the assembly there—and often that copying is the only step required in
the deployment.
Managed code runs in the Common Language Runtime. The runtime offers a wide
variety of services to your running code.
Managed code is code that is written to target the services of the managed
runtime execution environment (like Common Language Runtime in .NET
Framework).
Applications written in Java, C#, VB.NET, etc target a runtime environment which
manages the execution and the code written using these types of languages is
known as Managed Code.
Managed code provides information (i.e., metadata) to allow the CLR to locate
methods encoded in assembly modules, store and retrieve security information,
handle exceptions, and walk the program stack.
Managed code can access both managed data and unmanaged data.
Managed data—Memory that is allocated and released by the CLR using Garbage
Collection.
Managed code supplies the metadata necessary for the CLR to provide services
such as memory management, cross-language integration, code access security,
and automatic lifetime control of objects. All code based on IL executes as
managed code.
128
What is Unmanaged Code?
Code that does not target the common language runtime is known as unmanaged
code
Unmanaged code is what you use to make before Visual Studio .NET 2002 was
released.
Unmanaged code is always compiled to target a specific architecture and will only
run on the intended platform. This means that if you want to run the same code
on different architecture then you will have to recompile the code using that
particular architecture.
In unmanaged code the memory allocation, type safety, security, etc needs to be
taken care of by the developer.
Unmanaged executable files are basically a binary image, x86 code, loaded into
memory.
Managed Code
1. Understandable by CLR.
2. It is executed under the instructions of CLR.
3. Compiled two times.In the first compilation, the compiler will generate MSIL
code.Which is known as Managed Code.
UnManaged Code
1. Can not able to understand the code.
2. The CLR cannot instruct the code.
3. The second time compilation is unmanaged code.It is understood only by the
machine not by the user.
129
Exercise 3
Q.2 Compare
130
Chapter - 3
What is Control?
A control is an object that can be drawn on to the Form.
The controls are to enable or enhance user interaction with the application.
We can work with controls in two ways: at design time and at runtime.
We can add controls from the Toolbox at design time as given below:
With txt
.Text = "Enter"
.ForeColor = Color.Red
.Name = "txtNo"
.Top = 10
.Left = 10
131
.Width = 200
End With
With btn
.Text = "Click me"
.BackColor = Color.Gold
.ForeColor = Color.Green
.Name = "btnHai"
.Top = 10
.Left = 210
End With
Me.Controls.Add(btn)
Me.Controls.Add(txt)
End Sub
Property Description
BackColor Gets/Sets the background color
BackgroundImage Gets/Sets the background image
Bottom Gets the distance bewteen the bottom of the control and the top
of its container client area
ContextMenu Gets/Sets the shortcut menu for the control
Cursor Gets/Sets the cursor to be displayed when the user moves the
mouse over the form
Enabled Gets/Sets a value indicating if the control is enabled
Font Gets/Sets the font for the control
ForeColor Gets/Sets the font color (foreground) of the control
Height Gets/Sets the height of the control
Left Gets/Sets the x-coordinates of a control's left edge in pixels
Location Gets/Sets the co-ordinates of the upper-left corner of the control
Locked Gets/Sets the resize or move the control at design time.
Name Gets/Sets name for the control
Right Returns the distance between the right edge of the control and
the left edge of it's container
Size Gets/Sets size of the control in pixels
TabIndex Gets/Sets the tab order of this control in its container
TabStop Gets/Sets a value specifying if the user can Tab or shift+Tab to
this control with the tab key
Text Gets/Sets the text for this control
Top Gets/Sets the top coordinates of the control
Visible Gets/Sets a value for visibility of the control
Width Gets/Sets the width of the control
Event Description
Click Occurs when the control is clicked.
KeyDown Occurs when a key is pressed while the control has focus.
132
KeyPress Occurs when a key is pressed while the control has focus.
KeyUp Occurs when a key is released while the control has focus.
MouseDown Occurs when the mouse pointer is over the control and a mouse
button is pressed.
MouseMove Occurs when the mouse pointer is moved over the control.
MouseUp Occurs when the mouse pointer is over the control and a mouse
button is released.
MouseWheel Occurs when the mouse wheel moves while the control has focus.
TabOrder
The tab order is the order in which a user moves focus from one control to another by
pressing the TAB key.
Using Taborder property we can set the sequence of the TAB key for the controls.
There are 2 properties related with TabOrder are TabStop and TabIndex.
All the controls have TabStop property and the default value is True for setting the Tab
Order.
TabStop indicates if this control can accept the focus when the user Tabs to it
TabIndex is used for set the index of the control in the Taborder sequence.Statrting
value of the TabIndex 0.
When we set Taborder and then press TAB the focus of the control jump for one
control to other.
Using SHIFT + TAB use can focus the control in reverse order.
Property Window
Design View
133
TextBox Control
Windows users should be familiar with textboxes. This control looks like a box and
accepts input from the user.
TextBoxes are used to accept input from the user or used to display text.
Multiline TextBox
AcceptsTab
If True then we can enter tabs in a multiline text box using the TAB key; if False
then pressing the TAB key focus can moves the other control.
134
The default value is False.
BorderStyle – The border style can be Fixed3D (3D border), Fixed Single (single-line
border) or None (No border).
Cursor - The cursor that appears when the mouse passes over the
control.
Enable
MaxLength
It specifies the maximum number of characters that can be entered into the
TextBox.
0 means no limit.
MultiLine
If set True then we can increase the height of the TextBox control.
PasswordChar
135
Indicates the character as a Password.
ReadOnly
TabStop - Indicates whether the user can use the Tab key to give focus to the control
ClearUndo - Redo
Paste
txtData.Cut()
End Sub
136
txtData.Copy()
txtData.Paste()
End Sub
Private Sub btnUndo_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnUndo.Click
txtData.Undo()
End Sub
Private Sub btnRedo_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnRedo.Click
End Sub
txtData.Clear()
End Sub
Private Sub btnUcase_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnUcase.Click
txtData.Text = UCase(txtData.Text)
End Sub
txtData.Text = LCase(txtData.Text)
End Sub
KeyDown – Fires when a key is pressed down while the control has focus.
KeyPress – Fires when a key is pressed while the control has focus.
KeyUp - Fires when a key is released while the control has focus.
137
Example: Enter restricted data only
End Sub
End Sub
138
ErrorProvider Control
It allows us to set an error message for any control on the form when the input is not
valid according to our logic.
When icon indicating the error, take mouse over to that ErrorProvider control it will
display the message as Tool Tip.
Button control
Some Properties of the Button are Name, Text, BackColor, ForeColor, etc.
We can define accelerator keys on menus and command buttons by placing the
ampersand character (&) somewhere in the text of the menu or button.
For example set text property of the btnAns(button) as &Ans. It will display
underline under the character A now we can call btnAns button‘s event by ALT+A.
Ans
The default event of the Button is the Click event. When a Button is clicked it responds
with the Click Event.
Label Control
139
Mostly the Label control is used for displaying the answers and meaningful
notation.
140
RadioButton control
We can take RadioButton on the form when multiple options are there and
selection is only one. Like gender, stream, initial name, etc.
When the user checks one radio button within a group, the others get unchecked.
To create multiple groups on one form, place each group in its own container,
such as a GroupBox or Panel control.
Example:
Here the name of TextBox is txtName, Radiobutton names are optMale, optFemale and
Button name is btnAns.
Else
End If
End Sub
141
Example: According to RadioButton selection display the appropriate image on
lable control.
PictureBox1.Image = Image.FromFile("e:\Boy.gif")
End Sub
Output
PictureBox1.Image = Image.FromFile("e:\Girl.gif")
End Sub
PictureBox control
Notable properties of the PictureBox Control are Image, SizeMode, BorderStyle, etc.
Example: Problem is like user wants to view how many types of seats are
available for the admission in BCA and BBA.
Over here we have to take either GroupBox or Panel control to create two groups of
RadioButton.
lblAns.Text = 50
Output
ElseIf optNormal.Checked = True Then
lblAns.Text = 30
142
lblAns.Text = 15
End If
lblAns.Text = 70
lblAns.Text = 10
lblAns.Text = 5
End If
End If
End Sub
143
GroupBox and Panel
The typical use for a GroupBox and Panel is to contain a logical group of
RadioButton controls.
If we have two group boxes, each containing several radio buttons, each group of
buttons is mutually exclusive, setting one option value per group.
If the Panel‘s or GroupBox‘s Enabled property is set to False then the controls
which the Panel or GroupBox contains are also disabled.
Differences
GroupBox Panel
144
CheckBox control
We can use CheckBox controls in groups to display multiple choices from which
the user can select one or more.
The difference between CheckBox and RadioButton is: Any number of CheckBox
controls on a form can be selected and only one RadioButton in a group can be
selected.
Checked – True or False, which indicates the state of the CheckBox whether the
CheckBox is Checked or UnChecked.
CheckState Display
Checked The check box displays a check mark.
Unchecked The check box is empty.
Indeterminate The check box displays a check mark and is shaded.
User can Checked or Unchecked the CheckBox. But user can not do Indeterminate.
Output
What is the use of Indeterminate State? (Ask to your faculty)
The usefull event of the checkbox is CheckChanged event it calls when user
checked or unchecked the CheckBox.
145
Private Sub chkSports_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles chkSports.CheckedChanged
End If
End Sub
146
ListBox Control
A ListBox control displays a list of items from which the user can select one or more.
List boxes are best used for displaying large number of choices.
CheckBox control occupies space in the form. For example, If we give 50 chocies
to the user and if we use checkboxes for it then our form will be filled with
checkboxes only moreover, it occupies more space.Instead we give 50 choices in
the ListBox then it will look better and neat.
lstCity.Items.Add("Ahmedabad")
lstCity.Items.Add("Rajkot")
lstCity.Items.Add("Surat")
lstCity.Items.Add("Baroda")
lstCity.Items.Add("Junagadh")
End Sub
Output
Example: From the property window Add items in the ListBox.
Property Window
Editor
When we click on Items property of the ListBox then we can view as given above editor.
Type the list of the data as we want. The list will add Items design time.
147
Design View
MultiCoulmn – True or False. Set True for display items in the MultiColumn.
ScrollAlwaysVisible – True or False. Whether the vertical scroll bar is appears or not.
Value Description
MultiExtended Multiple items can select + user can use the SHIFT, CTRL, and arrow
keys to make selections
MultiSimple Multiple items can select
None No items can select
One Only one item can select (Default)
lstBox lstMode
148
ElseIf lstMode.SelectedItem = "One" Then
lstBox.SelectionMode = SelectionMode.One
End If
End Sub
Sorted – True or False. The items in the ListBox are sorted or not.
Selected Item
It is read-only property.
If more than one item is selected, the property returns the item with the
1st one.
Selected Items
This read-only property returns text of all the items selected in the ListBox.
SelectedIndex
It is read-only property.
If more than one item is selected, this property represents the lowest index.
SelectedIndices
This read-only property returns all the indices of selected items in the ListBox.
lstCity.Items.Add("Ahmedabad")
lstCity.Items.Add("Rajkot")
lstCity.Items.Add("Surat")
lstCity.Items.Add("Baroda")
lstCity.Items.Add("Junagadh")
End Sub
149
Private Sub btnSelectedIndex_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSelectedIndex.Click
End Sub
End Sub
Dim i As Integer
For i = 0 To lstCity.SelectedIndices.Count - 1
MsgBox(lstCity.SelectedIndices.Item(i))
Next
End Sub
Dim i As Integer
For i = 0 To lstCity.SelectedItems.Count - 1
MsgBox(lstCity.SelectedItems.Item(i))
Next
End Sub
Example: lstCity.ClearSelected
FindString() – It returns the index of the occurance of particular String. If not match
then returns -1.
Example: MsgBox(lstCity.FindString("Rajkot"))
150
Example: MsgBox(lstCity.GetSelected(0))
Example:
lstCity.SetSelected(3, True)
lstCity.SetSelected(4, False)
Dim i As Integer
lstCity.SetSelected(i, True)
Next
Dim i As Integer
Dim str As String = ""
Next
MsgBox(str)
End Sub
151
Items collection
Example: MsgBox(lstName.Items.Item(0))
Example:
lstName.Items.Add("Mansi")
Example:
With lstName.Items
.Add("Kruti")
.Add("Manav")
.Add("Niyati")
End With
Example:
lstName.Items.Add(Item_name)
str_Array(0) = "Mumbai"
str_Array(1) = "Ahmedabad"
str_Array(2) = "Junagadh"
str_Array(3) = "Rajkot"
str_Array(4) = "Surat"
lstCity.Items.AddRange(str_Array)
Example: lstName.Items.Clear()
152
Contains()
Example:
IndexOf() – It returns an index of the item listed in the list. If not found then it returns
-1.
Example: MsgBox(lstName.Items.IndexOf("Abhi"))
Insert()
We can insert item in the ListBox in any place by using Insert method.
Remove() – It removes the item from the ListBox. The argument of Remove() method
is the object.
Example: lstName.Items.Remove("Ripal")
Example: lstName.Items.RemoveAt(0)
lstName.Items.Add(txtName.Text)
txtName.Clear()
End Sub
If lstName.Items.Contains(txtName.Text) Then
Output
153
lstName.Items.Remove(txtName.Text)
End If
txtName.Clear()
End Sub
lstName.Items.Insert(txtPos.Text, txtVal.Text)
txtPos.Clear()
txtVal.Clear()
End Sub
lstYourMenu.Items.Add(lstMenu.SelectedItem)
lstMenu.Items.Remove(lstMenu.SelectedItem)
End Sub
End Sub
Dim i As Integer
For i = 0 To lstMenu.Items.Count - 1
lstYourMenu.Items.Add(lstMenu.Items.Item(i))
Next
lstMenu.Items.Clear()
End Sub
Dim i As Integer
For i = 0 To lstYourMenu.Items.Count - 1
lstMenu.Items.Add(lstYourMenu.Items.Item(i))
Next
154
lstYourMenu.Items.Clear()
End Sub
Dim i As Integer
For i = 0 To lstMenu.SelectedItems.Count - 1
lstYourMenu.Items.Add(lstMenu.SelectedItems.Item(0))
lstMenu.Items.Remove(lstMenu.SelectedItems.Item(0))
Next
End Sub
For i = 0 To lstYourMenu.SelectedItems.Count - 1
lstMenu.Items.Add(lstYourMenu.SelectedItems.Item(0))
lstYourMenu.Items.Remove(lstYourMenu.SelectedItems.Item(0))
Next
End Sub
155
CheckedListBox Control
Displays a ListBox in which a check box is displayed to the left of each item.
CheckedListBox is derived from the ListBox it shares all the members of ListBox.
CheckOnClick – True or False. if set True then check box is checked with the first click
of an item.
Example: MsgBox(chklstHobby.GetItemChecked(0))
Example: chkLstHobby.SetItemChecked(0,True)
For i = 0 To chkLstMovie.Items.Count - 1
156
str = chkLstMovie.Items.Item(i)
chkLstMovie.SetItemChecked(i, True)
Else
chkLstMovie.SetItemChecked(i, False)
End If
Next
End Sub
For i = 0 To chkLstMovie.Items.Count - 1
chkLstMovie.SetItemChecked(i, False)
Next
End Sub
Dim i As Integer
Dim str As String = ""
For i = 0 To chkLstMovie.Items.Count - 1
End If
Next
Output
MsgBox(str, MsgBoxStyle.Information, "Ans")
End Sub
GetItemCheckState() - Returns a value indicating the check state of the current item.
Example: Set Indeterminate state to even items and for odd set Checked state.
157
Private Sub btnCheckedState_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCheckedState.Click
Dim i As Integer
For i = 0 To chkLstMovie.Items.Count - 1
If i Mod 2 = 0 Then
chkLstMovie.SetItemCheckState(i, CheckState.Indeterminate)
Else
chkLstMovie.SetItemCheckState(i, CheckState.Checked)
End If
Next
End Sub
Dim i As Integer
For i = 0 To chkLstMovie.Items.Count - 1
Output
chkLstMovie.SetItemCheckState(i, CheckState.Unchecked)
Next
End Sub
158
ComboBox Control
RunTime user can enter new data to the ComboBox control but new data store in
it temporary.
User can select only one item from the given list.
It takes little space on the form and store long selection data.
By default, the ComboBox control appears in two parts: Top part + List part
The top part is a text box that allows the user to type a list item.
The list part displays a list of items from which the user can select one.
For example ,use ComboBox for list of Cities, list of Countries, etc.
We can add items, remove items and check items, etc are same as ListBox
control.
The combo box has three different DropDown Style (Property): Simple, drop
down, and drop-down list.
Simple
159
The text portion is editable.
The user must click the arrow button to display the list portion.
DropDownList DropDown
DropDownList
The ComboBox has same Items collection as ListBox and CheckedListBox control.
Set MaxDropDownItems=2
Property Window
Output
160
Sorted - True or False. Gets or sets whether the items in the combo box are sorted.
cmbCity.Items.Remove(cmbCity.SelectedItem)
End Sub
cmbCity.Items.RemoveAt(cmbCity.SelectedIndex)
End Sub
End Sub
161
MsgBox(cmbCity.SelectedIndex)
End Sub
MsgBox(cmbCity.SelectedItem)
End Sub
cmbCity.Items.Clear()
End Sub
MsgBox(cmbCity.Items.Count)
End Sub
Example: Take 2 CombBox set their name like cmbRollNo which contains
numbers of the student , second one cmbName which contains names of the
student. When we select rollno then name of the student should display vice
versa.
Output
With cmbRollNo.Items
.Add("1")
.Add("2")
.Add("3")
.Add("4")
.Add("5")
.Add("6")
End With
With cmbName.Items
.Add("Ritu")
.Add("Pooja")
.Add("Jigar")
.Add("Mayur")
162
.Add("Parul")
.Add("Aalok")
End With
End Sub
cmbName.SelectedIndex = cmbRollNo.SelectedIndex
End Sub
cmbRollNo.SelectedIndex = cmbName.SelectedIndex
End Sub
163
ScrollBar Control
For example,When there are number of records and we want to view 3400
positioned record then button control is not help properly it takes time. We should
give user to ScrollBar or TrackBar control.
In Microsoft Word or Excel we can see left and bottom side Scrollbar.
The left end of the ScrollBar corresponds to its minimum value; the other end is
the ScrollBar‘s maximum value.
The current value of the control is assumed by the position of the indicatior.
SmallChange
LargeChange
Minimum
Maximum
Property Window
164
SmallChange
When we click on most left and right side arrows of the Scrollbar the Scrollbar
moves in small amount it called SmallChange.
When we click on most left arrow the value property of the Scrollbar will decrease
or subtract.
When we click on most right arrow the value property of the Scrollbar will
increase or add.
LargeChange
When we click in between indicator and left or right side arrow it is called
LargeChange.
Value
200-10+1 = 191
209-10+1= 200
165
The scrollbar‟s events fire when
Scroll Event
Fires when the Value property has changed, either by a Scroll event or
programmatically.
We can not get any information from “e” argument of ValueChanged event as
above image.
Output
166
Private Sub btnMax_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMax.Click
Else
End If
End Sub
pict_Path(0) = "e:\1.jpg"
pict_Path(1) = "e:\2.jpg"
pict_Path(2) = "e:\3.jpg"
pict_Path(3) = "e:\4.jpg"
pict_Path(4) = "e:\5.jpg"
With HScrollBar1
.Maximum = 7
.Minimum = 1 Output
.SmallChange = 1
.LargeChange = 3
.Value = 1
End With
PictureBox1.Image = Image.FromFile(pict_Path(0))
End Sub
Me.Text = HScrollBar1.Value
End Sub
167
TrackBar Control
The user can change the value of the TrackBar by dragging the slider, using the arrow
keys, Page Up or Page Down keys.
TrackBar control has same properties ,events and methods like ScrollBar.
TickStyle
1. None
2. TopLeft
3. BottomRight
4. Both
168
TickFrquency
PBTM= 50/5
PBTM =10
PBTM = 50/10
PBTM =5
Output
lblAns.Text = ""
Dim i As Integer
For i = 1 To 10
lblAns.Text &= TrackBar1.Value & " X " & i & " = " & (TrackBar1.Value * i) & vbNewLine
Next
169
End Sub
Example: Change the background color of the form using 3 TrackBar‟s value.
Set range of all TrackBar is 0 to 255 and Here we are using common event
handler.Because all 3 TrackBar‘s logic are same.
Property Window
Output
Me.BackColor=Color.FromArgb(TrackBarRed.Value,TrackBarGreen.Value,TrackBarBlue.
Value)
lblRed.Text = TrackBarRed.Value
lblGreen.Text = TrackBarGreen.Value
lblBlue.Text = TrackBarBlue.Value
End Sub
170
Common Dialog Control
VB.NET contains built-in dialog boxes which allow us to create our own File Open, File
Save, Font, and Color dialogs control like we see in all the windows applications.
1. Color Dialog
2. Font Dialog
3. Open file Dialog
4. Save file Dialog
5. Print Dialog
6. PrintPreviewDialog
7. PageSetupDialog
To use any Common Dialog Control just add that control to our form as give below
image.
Design View
Here we are going to view Common dialog controls with RichTextBox control.
RichTextBox control is an advance version of the TextBox control.
Return type
of DialogBox
Coding Window
171
Usually we are writing the code if DialogBox return of Ok. Means when user press Ok
that time.
ColorDialog
Property Window
AllowFullOpen True
True or False.
False
Default value is True.
When set to False, the button of Define Custom Colors in the dialog box is
disabled and the user cannot define the custom colors.
Color
If we set this property before opening the Color dialog box,the selected color will
display on the Color dialog box.
Runtime(Coding)
With ColorDialog1
172
.Color = Color.Orange
End If
End With
End Sub
Output:
FullOpen
True or False
If we want to give default color dialog with custom color then set value True for
the FullOpen property.
Property Window
173
End Sub
RichTextBox1.BackColor = ColorDialog1.Color
End If
End Sub
RichTextBox1.ForeColor = ColorDialog1.Color
End If
End Sub
174
FontDialog
AllowSimulations
ShowApply
MaxSize,MinSize
ShowEffect
ShowColor
AllowScriptChange
AllowSimulations
True or False.
AllowScriptChange
True or False.
Property Window
175
Whether the user can change the character set specified in the Script.
Color
True or False.
Font
MaxSize , MinSize
Default values are 0 means, there are are no font size limits.
Set
Output
ShowApply
True or False
ShowColor
True or False
ShowEffects
Whether the dialog box contains controls that allow the user to specify
strikethrough, underline, and text color options.
True or False.
If False 176
Example: On click of button open font dialog and apply effect.
Output
With FontDialog1
RichTextBox1.Font = .Font
RichTextBox1.ForeColor = .Color
End If
End With
End Sub
177
OpenFileDialog
Property Window
CheckFileExists
Boolean value.
Whether a warning message should be displayed if the user wants to open the
name of a file that does not exist.
FileName property
Returns a string that contains the complete path and filename of the selected file
Output
178
Private Sub btnFileOpen_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFileOpen.Click
End If
End Sub
Filter property
Hai Text File title will display to user and filter the
files using *.txt
Output
179
Exmaple: Set filter property using coding and multiple filters.
Output
RTxt.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.PlainText)
End If
End Sub
180
Example: Using OpenFile dialog open Image in PicuteBox control
Click on Button
Output
181
Private Sub btnFileOpen_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFileOpen.Click
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
FilterIndex property
Which default Filter value will show to user? Each filter value has an index.
Example:
If we write
Then
InitialDirectory property
With OpenFileDialog1
.InitialDirectory = "c:\"
End With
182
ReadOnlyChecked
Boolean value.
ShowReadOnly
Boolean value.
Title property
Example:
SaveFileDialog
Basically it is SaveAs file dialog. The default title of SaveFile dialog box is Save As.
Properties of the Save File Dialog are the same as that of the Open File Dialog.
183
Private Sub btnFileSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFileSave.Click
With SaveFileDialog1
RText.SaveFile(.FileName, RichTextBoxStreamType.PlainText)
End If
End With
End Sub
184
RichTextBox Control
The wordpad save it‘s file in RTF format. The full form of RTF is Rich Text Format.
RichTextBox allows formatting the text, say adding colors, displaying particular
font types,selected text effect, bullets, alignment,indents and so on.
We are going to create Notepad, during it we can learn the advance features of
RichTextBox.
File->New,Open,Save,SaveAs,Exit
Edit->Undo,Redo,Cut,Copy,Paste,SelectAll
Format->Font->Selected
->All
->Color->Selected
->All
->Alignment->Left
->Center
->Right
->Bullet
View->Zoom->5
->10
AboutMe
185
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles NewToolStripMenuItem.Click
'New file
richTxt.SaveFile(Me.Text, RichTextBoxStreamType.PlainText)
Me.Text = "Notepad"
richTxt.Clear()
Else
End If
End Sub
'Open
With OpenFileDialog1
richTxt.LoadFile(.FileName, RichTextBoxStreamType.PlainText)
Me.Text = .FileName
End If
End With
End Sub
'Save
With SaveFileDialog1
richTxt.SaveFile(.FileName, RichTextBoxStreamType.PlainText)
186
Me.Text = .FileName
End If
End With
Else
richTxt.SaveFile(Me.Text, RichTextBoxStreamType.PlainText)
End If
End Sub
'Save As
With SaveFileDialog1
richTxt.SaveFile(.FileName, RichTextBoxStreamType.PlainText)
Me.Text = .FileName
End If
End With
End Sub
End
End Sub
richTxt.Undo()
End Sub
richTxt.Redo()
187
End Sub
richTxt.Cut()
End Sub
richTxt.Copy()
End Sub
richTxt.Paste()
End Sub
richTxt.SelectAll()
End Sub
'Font->Selected
With FontDialog1
richTxt.SelectionFont = .Font
End If
End With
End Sub
'Font->All
With FontDialog1
188
richTxt.Font = .Font
End If
End With
End Sub
'Color->Selected
With ColorDialog1
End With
End Sub
Private Sub AllToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles AllToolStripMenuItem1.Click
'Color->All
With ColorDialog1
End With
End Sub
richTxt.SelectionAlignment = HorizontalAlignment.Right
End Sub
richTxt.SelectionAlignment = HorizontalAlignment.Left
End Sub
richTxt.SelectionAlignment = HorizontalAlignment.Center
End Sub
189
Private Sub BulletToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BulletToolStripMenuItem.Click
richTxt.BulletIndent = 2
richTxt.SelectionBullet = True
End Sub
richTxt.ZoomFactor = 2
End Sub
richTxt.ZoomFactor = 5
End Sub
richTxt.ZoomFactor = 10
End Sub
End Sub
190
TreeView Control
We can display TreeView control with check boxes next to the nodes, if the
TreeView's CheckBoxes property is set to true
Example: Drag and Drop Treeview control on form then click on Nodes property.
Output
Property Window
191
The ListBox and ComboBox control have Items property and we can add item in the
Items property same over here the TreeView control have Nodes property.
Coding Window
Properties of TreeView
Nodes collection
Example: MsgBox(tvHMall.Nodes.Count)
Example:
node = tvHMall.Nodes.Item(1)
MsgBox(node.Text)
End Sub
Example:
tvHMall.Nodes.Add("Mumbai")
Example:
With tvHMall.Nodes
.Add("Mumbai")
192
.Add("Noida")
.Add("Delhi")
.Add("Ahmedabad")
End With
Example:
tvHMall.Nodes.Add(Item_name)
Example:
tvHMall.SelectedNode.Nodes.AddRange(strNodes)
Example: tvHMall.Nodes.Clear()
Contains()
Example:
Insert()
We can insert node in the Treeview in any place by using Insert method.
Example:
193
node.Text = "Nano"
tvCar.Nodes.Insert(1, node)
Remove() – It removes the node from the Treeview. The argument of Remove()
method is the node.
Example: tvCar.Nodes.Remove(node)
Example: tvCar.Nodes.RemoveAt(0)
Selected Node
MsgBox(tvCities.SelectedNode.Text)
End Sub
MsgBox(tvCities.SelectedNode.Nodes(0).Text)
MsgBox(tvCities.SelectedNode.Nodes(1).Text)
MsgBox(tvCities.SelectedNode.Nodes(2).Text)
Output
End Sub
Check this
MsgBox(tvHMall.SelectedNode.NextNode.Text)
MsgBox(tvHMall.SelectedNode.LastNode.Text)
MsgBox(tvHMall.SelectedNode.PrevNode.Text)
Node Identification
Ahmedabad tvCities.Nodes(0)
Mumbai tvCities.Nodes(1)
Gurukul tvCities.Nodes(0).Nodes(0)
DriveIn tvCities.Nodes(0).Nodes(1)
Bopal tvCities.Nodes(0).Nodes(2)
Kandivali tvCities.Nodes(1).Nodes(0)
Borivali tvCities.Nodes(1).Nodes(1)
Malad tvCities.Nodes(1).Nodes(2)
194
Example: Demo of Add, Remove,Clear,Expand,Collapse methods.
tvHMall.Nodes.Add(txtData.Text)
End Sub
End Sub
tvHMall.SelectedNode.Remove()
End Sub
tvHMall.Nodes.Clear()
End Sub
Output
Private Sub btnCollapse_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCollapse.Click
tvHMall.CollapseAll()
End Sub
tvHMall.ExpandAll()
End Sub
MsgBox(tvHMall.Nodes.Count)
End Sub
CheckBoxes
True or False
195
Display checkbox with TreeView‘s node.
HotTracking
True or False
Nodes get hyperlink effect when the mouse is moved over them.
ShowLines
True or False
ShowPlusMinus
True or False
ShowRootLines
True or False
FullPath
Example:
MsgBox(tvHMall.SelectedNode.FullPath)
BCA\GLS
PathSeparator
Default event of the Tree View control is the AfterSelect event. It fires after the tree
node is selected.
196
TreeView control can work with ImageList control. The advantage of using the
ImageList is that we can treat the images as a collection. The ImageList control is used
to store images, which can display by other controls like ListView, TreeView, etc. To
work with ImageList follows the below given steps:
Property Window
Step 3: Select the name of ImageList control from TreeView control‘s ImageList
property and set SelectedImageIndex property (Image for selected node).
Property Window
197
ListView Control
It allows you to add rows of data, but it also supports large and small icons, multiple
columns, automatic label edit, column re-order, hot-tracking, and the four main modes
that you see in explorer:
1. Large Icon - Displays items with large icons and your main text
2. Small Icon - Displays items with small icons and your main text
3. List - Displays items with your main text
4. Detail - Displays items with small icons, your main text, and any other data to be
displayed in columns.
We can add items at design time using Items editor.For it click on Items property.
198
Coding:
ListView1.View = View.Details
ListView1.Items.Add("Yash C.")
ListView1.Items.Add("Sanjay B.")
ListView1.Items.Add("Rakesh R.")
ListView1.Items(0).SubItems.Add("Lamhe")
ListView1.Items(0).SubItems.Add("Good")
ListView1.Items(1).SubItems.Add("Devdas")
ListView1.Items(1).SubItems.Add("Ok")
ListView1.Items(2).SubItems.Add("Krish")
ListView1.Items(2).SubItems.Add("Good")
End Sub
Example: Take Listview and one drop down contains different views on change of
ComboBox see the effect
199
ListView1.View = View.LargeIcon
ElseIf str = "Details" Then
ListView1.View = View.Details
Else
ListView1.View = View.List
End If
End Sub
200
Exercise-4
Q.1 Explain the following controls with its properties ,methods and events.
1. TrackBar
2. ScrollBar
3. ListBox
4. ComboBox
5. CheckedListBox
6. ScrollBar
7. TrackBar
8. RichTextBox
9. TreeView
10. ListView
Q.3 Compare
201
8. We can not specify path of the selected node.
Q.6 Practical
TextBox
1. Create Login form and if username and password are right then MDI form will
open.
Trackbar
3. Depending upon the trackbar‘s position the picture will display in the picture box.
4. There are 3 Trackbars on the Form. First Trackbar stands for Red, second for
Green and third for Blue, and it depends on the position of indicator the
background color of label will display.
6. Compare two trackbar‘s value as per the value selected in both of them, you have
to display that which track bar is having the Maximum and which one is the
Minimum value.
Scrollbar
202
9. Depending upon the scrollbar‘s position the picture will display in the picture box.
10. There are 3 scrollbars on the Form.First scrollbar stands for Red, second for
Green and third for Blue, and it depends on the position of indicator the
background color of label will display.
14. Compare two scrollbar‘s value as per the value selected in both of them, you
have to display that which scrollbar is having the Maximum and which one is the
Minimum value.
Combo Box
16
203
ListBox
20 Take 6 buttons and 2 listboxes. If we click on > then shift single selected item from
listbox1 to listbox2. If we click on >> then shift selected items from listbox1 to listbox2.
If we click on >>> then shift all the items from listbox1 to listbox2. (Viceversa for
<,<<,<<<)
204
21 Take 2 Listboxes.Listbox1 contains A…Z and Listbox2 contains name of the students.
If we select A then the names starting from A will be selected.
205
CheckBoxList
206
25
207
26 Take 4 buttons and 2 Checkedlistboxes. If we click on > then shift single checked
item from Checkedlistbox1 to Checkedlistbox2. If we click on >> then shift checked
items from Checkedlistbox1 to Checkedlistbox2.
27
Create an order form which contains checkedistbox for different item as above also
display their price in labels and allow the user to enter their quantity in textboxes and on
the click of ‗Bill‘ print the total checked items‘s bill.
28
208
treeview2.
30 Take one textbox and treeview.Enter the value in textbox and select operation from
treeview and display answer in the label.
209
Chapter 5
Object Oriented
A major factor in the invention of Object-Oriented approach is to remove the
problems of the procedural approach.
In OOP, data is treated as an important element and does not allow it to flow
freely.
It bounds data closely to the functions that operate on it and protects it from
accidental modification from outside functions.
Classes are collection of objects. It is blueprint for the object. It‘s a combination of
Data Members + Data Functions.
Just as a blueprint can be used to create multiple buildings, a single class can be
used to create as many objects as necessary.
VB.NET supports all the main OOP features like Polymorphism, Inheritance,
Abstraction and Encapsulation.
210
Overview of basic concepts of OOP:
Classes
Once a class is defined, any number of objects can be created which belong to
that class.
Objects
Polymorphism
Encapsulation
Data Abstraction
211
Inheritance
The new class will have combined features of both the classes.
It provides reusability.
Advantages of OOP
Details are hidden and the unit has a clearly defined interface.
Programs are easy to maintain and modify existing code.We can easily add or
modify function or member.
212
Let‘s start with the example of Class
Add new class to the project and give proper name to the class. The extension of the
class is .vb.
Coding Window
213
Add Form to the project design it.We create the object of the class in the Windows form.
After we type the word "As", then hit the spacebar, popup box appear. If we type the
letters "cls", the list automatically move down. The Class we created appears in that list,
as in the next image:
Coding Window
As soon as we type a full stop(.) after the obj, a popup box with the name of our new
method on the list because they are procedures or say part of the class clsMath.
Coding Window
Final coding:
End Sub
214
Property
A Property procedure is the 4th type of procedure.
Property procedures are executed when the property value is set or retrieved.
According oops concept user does not allow working directly with the data
members of the class so we have to create properties for get or set the values of
data members.
When user creates object, user interacts with the properties of the class not the
data mebers of the class so we should give proper name to the properties.
For example, txtAns.Text, Text is the property of TextBox class and from the
‗Text‘ name we can easily get the meaning that it will set or get Text value of the
TextBox class.
Syntax:
Get
Return varName
End Get
End Property
Example:
Write down the name of the property and then just press enter.
Coding Window
215
After pressing Enter key
Rollno property is related with m_no data member.
Coding Window
Example:
Get
Return m_no
End Get
End Property
Get
Return m_name
End Get
End Property
End Class
Properties are Public by default, which means we can call them from anywhere in our
application.
216
Coding Window
Dim obj As New clsStu
obj.Rollno = 5
obj.StuName = "Suresh Rathod"
MsgBox(obj.Rollno)
MsgBox(obj.StuName)
Set – Initalize
Get - Retrive
The Set area of the procedure is invoked when the application attempts to set the
property‘s value.
obj.Rollno = txtNo.Text
obj.StuName = "Suresh Rathod"
The Get procedures return the value of the data member. The Get area invoked
when the application requests the property‘s value.
txtAns.text =obj.Rollno
MsgBox(obj.StuName)
Above lines will get the values datamembers m_no and m_name.
Get
Return m_Age
End Get
End Property
It‘s depends on your requirement whether to create property with Get, Set (Read/Write)
or read-only (Get) or write-only (Set).
Get and Set property procedures to allow us to both read and modify the value
stored inside.
217
We can use the ReadOnly or WriteOnly modifiers to restrict properties from being
modified or read.
Read-only properties cannot have Set area.We can just reterive the value from
it.We can not modify the data member using Readonly property.
Write-only properties cannot have Get area. We can only set the value but does
not reterive the value. It‘s used for security putpose.
Example:
Get
Return m_no
End Get
Set(ByVal value As Integer)
m_no = value
End Set
End Property
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property
Get
Return "LJ CCA"
End Get
End Property
218
End Property
End Class
Write down below coding in the btnAns click , code will generate error.
Coding Window
Right coding
obj.Rollno = txtNo.Text
obj.StuName = txtName.Text
obj.Password = txtPwd.Text
MsgBox("No = " & obj.Rollno & " and Name = " & obj.StuName,
MsgBoxStyle.Information, obj.CollegeName)
End Sub
Output
219
Polymorphism
It means ―one name, multiple forms".
Function overloading means we can declare more then one function with the
same name but arguments are different. The function performs different
operations based on the argument list in the function call.
Example:
Return I
End Function
Return i + j
End Function
Return i + j + k
End Function
End Class
Coding Window
220
Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAns.Click
msgbox(obj.add(10))
msgbox(obj.add(10, 20))
End Sub
221
Inheritance
The new class will have combined features of both the classes.
The original class, from which we inherit interface and behavior is known by the
following interchangeable terms:
Parent class
Superclass
Base class
The new class that inherits the interface and behaviors is known by the following
terms:
Child class
Sub class
Derived class
A derive class receives all of the methods, properties, and events of the base
class.
The sizeof the sub class is always bigger than the size of super class‘s object.
Inherits
NotInheritable
MustInherit (abstract class)
222
Inherits
To create Parent – Child relationship between to classes we need to write Inherits
keyword.
The class contains Inherits keyword is called sub , child or derived class.
Example:
Logic…………………
End class
Logic……………………
End class
Base class
223
Derived class
Coding Window Windows Form
See the magic object of clsExtra contains base class clsEmp‘s properties.
Derived class object‘s contains = Base class‘s data members +data functions + Dervied
class‘s data members + data functions
obj.Name = txtName.Text
obj.Post = txtPost.Text
obj.Salary = txtSal.Text
obj.Bonus = txtBonus.Text
End Sub
Output
224
NotInheritable
It is also known as sealed class.
There are times when we might want to create a class that cannot be subclassed.
If there is a possibility that a class will be updated in the future and create the
problem, declare it as NotInheritable.
It gives surety that your class is not become parent of any class.
Example:
End Class
When this keyword is used, no other code may use the Inherits keyword to create
a subclass of our class.
clsA
Coding Window
clsB
225
MustInherit
In C++ and C#, we use the term abstract class to describe such a class.
In VB.NET if we wants to create abstract class then add the keyword MustInherit
in class declration.
It Specifies that the class is intended for use as a base class only.
Abstract classes can only specify members that should be implemented by all
inheriting classes
If our class contains atleast one MustOverride method then our class should be
declare as MustInherit class.
Syntax:
Logic………
End Sub
Example:
Coding Window
226
Coding Window
Methods written in above class as MustOverride are automatically appear in the derived
class.
MustOverride
No other statements are allowed, and specifically there is no End Sub or End
Function statement.
If your class contains any one method as a MustOverride keyword then your class
must have MustInherit keyword.
For example, if we remove clearData() sub procedure from derived class clsTemp then it
will generate an error as given below:
Coding Window
227
Example: Create Cpolygon class as abstract class having area () function.
Create CTriangle, CRectangle class based on this Cpolygon class. Design user
interface for this class.
End class
A class inheriting from this class would have to implement the Area() function
The following example shows what the implementation of this class might look like:
End Class
228
Public Overrides Function Area() As Double
Return Height * Width
End Function
End Class
If our class contains any one method with MustOverride keyword then we must have to
define our class as a MustInherit.
And the methods define as MustOverride should be redefined in the derived class.
Output
End Sub
End Class
229
Overriding
The overriding concept achieve only in Inheritance. It requires parent-child
relationship to implement.
Function overriding means when we declare more than one function with the
same name but in different class and the relationship between class is parent-
child.
The keyword Overrides is used to mark that a function is overriding some base
class function. It means finally we override base class‘s method.
The Overides keyword allows the inheriting class to redefine the property or
method of the inherited class and implements its own code.
230
Write Overridable keyword before
Function
Coding Window
NotOverridable
If we do not write any keyword before Function and Procedure then they are
default NotOverridable.
231
Constructor
A constructor is a special member function whose task is to initialize the objects
of its class.
This is the first method that is run when an instance of a type is created.
Synatx:
Sub New()
End sub
Sub New()
Rollnumber = 5
NameofStu = "Vishwaraj"
Fees = 1000
End Sub
232
End Get
Set(ByVal value As String)
m_Name = value
End Set
End Property
End Class
Coding in Form:
lblNo.Text = obj.Rollnumber
lblName.Text = obj.NameofStu
lblCollegeName.Text = obj.CollegeName
lblPrint.Text = obj.print
End Sub
Output
233
How to call base class constructor?
(Same like C++) As we know here we can create constructor without parameter as
below:
Sub New ()
End Sub
End Sub
Example:
Private x As Integer
Private y As Integer
Sub New()
x=0
y=0
End Sub
End Class
Private z As Integer
Sub New()
End Sub
234
z=c
End Sub
End Class
In the form:
End sub
MyBase keyword
MyBase refers to the immediate base class and its inherited members.
235
Destructors
A Destructor is a special function which is called automatically when a class is
destroyed.
This is called Finalize in VB.NET and it‘s called whenever the .NET runtime is told
directly or otherwise determines that an object is no longer required.
Within a destructor we can place code to clean up the object after it is used,
which might include decrementing counters or releasing resources.
When an instance is destructed, the destructors in its inheritance chain are called,
in order, from most derived to least derived.
Syntax:
If we write the code for manual memory management one has to take care both
allocation and de-allocation of memory. So there is probability that one can forget
de-allocation. And also manual memory management is time consuming and
complex process.
GC keeps tracks of all the objects and ensures that each object gets destroyed
once.
GC ensures that objects, which are being referenced, are not destroyed.
GC is a .net framework thread, which runs when needed or when other threads
are in suspended mode. So first GC creates the list of all the objects created in
the program by traversing the reference fields inside the objects. This list helps
the GC to know how many objects it needs to keep track.
Then it ensures that there are no circular references inside this list. In this list GC
then checks for all the objects, which have destructor, declared and place them in
another list called Finalization List.
236
Interface
Why Would I Want to Build an Interface?
We can not inherit more than one class in VB.NET. If we want to inherit then? Use
Interface.
Interface
Interfaces, like classes, define a set of properties, methods, and events. But
unlike classes, an interface does not contain any implementation code.
The classes which implement interface their respnosbility is to write the coding in
the interface‘s method.
Interface definitions are enclosed within the Interface and End Interface
statements.
Syntax:
End Interface
Example:
Example:
logic…..
237
End class
Coding Window
After pressing Enter key methods of Interfaces automatically appeared in the class.
And then we create the object of the above class in the button click and see the magic as
given below:
Coding Window
238
Flexibility in Implementation
Summary
Inherits
NotInheritable
MustInherit
Overridable
NotOverridable
MustOverride
Overrides
MyBase
MyClass
239
How to work in Console base?
From Solution explorer add new Module and Write down this below coding in
module
Application type
Startup Object
240
Now run your program
Sub main() function is like main() function of C and C++. The execution of the program
will start from that function.
Writeline and Write methods are like printf of C or cout of C++ language.
Readline and Red methods are like scanf of C or cin of C++ language.
Imports System.Console
Module Module1
Sub main()
Dim a, b As Integer
WriteLine("Enter no a ->")
a = ReadLine()
WriteLine("Enter no b ->")
b = ReadLine()
End Sub
End Module
Imports System.Console
Module Module1
Sub main()
Dim No As Integer
Dim name As String
241
WriteLine("Enter Name ->")
Name = ReadLine()
WriteLine("Enter No ->")
No = ReadLine()
Read()
End Sub
End Module
242
End Set
End Property
End Class
Now add module and write create the object inside sub main() function.
Imports System.Console
Module Module1
Sub main()
obj.X = 5
obj.Y = 10
WriteLine(ans)
Read()
End Sub
End Module
243
Array
One variable was holding one piece of information. An array is a variable that can
hold more than one piece of information at a time.
Example:
ar(0) = 1
ar(1) = 2
ar(2) = 3
ar(3) = 4
ar(4) = 5
When we declare an array with the Dim keyword, we should write the name of the array
and the size of the array.
In the above example we've set up an Integer array with 5 items in it. We've then said
put number 1 into array position 0, put number 2 into array position 1, put number 3
into array position 2, and so on.
In any other C or C++ if we declare the array with size (4) as above the we can store
only 4 items in array, but in VB.NET we can store upto that value upto 4.
The following example stores employee information in the array variable EmployeeData.
For i = 0 To 3
TextBox1.Text &= EmployeeData(i) & vbCrLf
Next
244
Array Dimensions
Multidimensional Arrays
The following statement declares a two-dimensional array with 5 rows and 10 columns.
The total number of elements is the product of the sizes of all the dimensions, in the
above case 5 * 10=50 elements can store in arrat.
The highest subscript value is returned by the GetUpperBound method for particular
dimension.
For example, the following statements initialize every element in Ar1 to a value between
0 and 35, based on its location in the array.
Dim I, J As Integer
MaxDim0 = Ar1.GetUpperBound(0)
'returns 5 from 1st dimension
MaxDim1 = Ar1.GetUpperBound(1)
'returns 5 from 2nd dimension
For I = 0 To MaxDim0
Next I
Remember that in C or C++ usually we run the loop upto length of that array but over
here it will not work. We should write the logic from 0 to GetUpperbound
ar(0) = "vedika"
245
ar(1) = InputBox("Enter value")
ar(2) = TextBox1.Text
ar.SetValue("hai", 3)
TextBox1.Text = ar(0)
MsgBox(ar(1))
MsgBox(ar.GetValue(2))
For i = 0 To ar.GetUpperBound(0)
MsgBox(ar(i))
Next
Common properties
Length
Example:
MsgBox(name.Length)
MsgBox(nameLen.Length)
Output:
7 [0-6]
35 [0-6 X 0-4 = 7X5 = 35]
GetLength
GetLength(1), which returns the number of elements that can be store in the 2nd
dimension of the Array.
Example:
MsgBox(name1.GetLength(0)) 'Returns 7
MsgBox(name2.GetLength(0)) 'Returns 6
MsgBox(name2.GetLength(1)) 'Returns 5
246
Rank
Example:
MsgBox(name.Rank)
MsgBox(mat.Rank)
GetUpperBound
GetLowerBound
Example:
Output:
1)Getupperbound = 6 GetLowerBound=0
2)Getupperbound = 6 GetLowerBound=0
3)Getupperbound = 4 GetLowerBound=0
Dim i, j As Integer
ar(0, 0) = 1
ar(0, 1) = 2
ar(0, 2) = 3
ar(1, 0) = 4
ar(1, 1) = 5
ar(1, 2) = 6
MsgBox(ar.Length)
247
MsgBox(ar.Rank)
MsgBox(ar.GetLength(0))
MsgBox(ar.GetLength(1))
MsgBox(ar.GetLowerBound(0))
MsgBox(ar.GetLowerBound(1))
MsgBox(ar.GetUpperBound(0))
MsgBox(ar.GetUpperBound(1))
For i = 0 To ar.GetUpperBound(0)
For j = 0 To ar.GetUpperBound(1)
Next
Length means total elements, Rank means dimension of the array,GetLength means
total elements that can store in particular dimension , GetLowerbound is always 0 and
GetUpperbound means highest index of specified dimension.
Common Methods
Clear
Array.Clear(name, 0, 1)
GetValue
Example:
name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"
name(3) = "Mayur"
name(4) = "Jaimin"
name(5) = "Ritu"
name(6) = "Gaurav"
Dim i As Integer
248
Output
For i = 0 To name.GetUpperBound(0)
ListBox1.Items.Add(name.GetValue(i))
Next
SetValue
Example:
name.SetValue("shyam", 0)
name.SetValue("meera", 1)
Example:
For i = 0 To name.GetUpperBound(0)
ListBox1.Items.Add(name.SetValue("a", i))
Output
Next
Sorting
name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"
name(3) = "Ritesh"
name(4) = "Jaimin"
name(5) = "Ritu"
name(6) = "Hitarth"
ListBox1.Items.AddRange(name)
System.Array.Sort(name)
ListBox2.Items.AddRange(name) Output
End Sub
249
Dim i As Integer
name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"
name(3) = "OM"
name(4) = "Jaimin"
name(5) = "Ritu"
name(6) = "Hitarth"
For i = 0 To name.GetUpperBound(0)
nameLen(i) = Len(name(i))
Next
For i = 0 To name.GetUpperBound(0)
lst1.Items.Add(name(i) & " " & Len(name(i)))
Next
System.Array.Sort(nameLen, name)
For i = 0 To UBound(name)
lst2.Items.Add(name(i) & " " & Len(name(i)))
Next
End Sub
ListBox1.Items.AddRange(name)
System.Array.Sort(name, 0, 4)
ListBox2.Items.AddRange(name)
End Sub
Output
Example 4: Search particular item
Dim i As Integer
Dim search_item As String
250
Dim name(6) As String
name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"
name(3) = "OM"
name(4) = "Jaimin"
name(5) = "Ritu"
name(6) = "Hitarth"
i = System.Array.IndexOf(name, search_item, 0)
txtIndex.Text = i
End Sub
name(0) = "Yash"
name(1) = "Arvind"
name(2) = "Aalok"
name(3) = "Anupa"
name(4) = "Shweta"
name(5) = "Ritu"
name(6) = "Hitarth"
ListBox1.Items.AddRange(name)
Array.Reverse(name)
Output
ListBox2.Items.AddRange(name)
Copy method
The sourceArray and destinationArray parameters must have the same number of
dimensions.
It copies a range of elements from oen array to another into particular index.
Copy To
It copies all the elements of the current one-dimensional array to another one-
dimensional array.
251
instance.CopyTo(array, index)
Example:
name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"
name.CopyTo(name2, 0)
In some cases, we may not know exactly the size of array at declaration time. We
may need to change the size of the array at runtime that time this concept will
use.
The size of a dynamic array can vary during depends on requirement of the
program.
Example:
ReDim tmpArray(cnt)
MsgBox(tmpArray.Length)
We can use a large array for a short time and then ReDim it to a smaller size. It
frees the memory.
Example:
Form_Load
Rollno(0) = 1
Rollno(1) = 2
252
Rollno(2) = 3
End sub
Example: Problem
Output
Dim i As Integer
For i = 0 To Rollno.GetUpperBound(0)
lstNo.Items.Add(Rollno(i))
Next
End Sub
Wrong one
Dim i As Integer
For i = 0 To Rollno.GetUpperBound(0)
lstTemp.Items.Add(Rollno(i))
Next
End Sub
We can keep those values by including the Preserve keyword in the ReDim
statement.
The ReDim statement recognizes the Preserve keyword, which forces it to resize
the array without discarding the existing data.
253
Example:
Output
Dim i As Integer
For i = 0 To Rollno.GetUpperBound(0)
lstTemp.Items.Add(Rollno(i))
Next
End Sub
254
Collection
A collection is a one-dimensional storage area.
Class Description
SortedList Represents a collection of key/value pairs that are sorted by the keys and
are accessible by key and by index.
A collection is declared with a Dim statement that creates a new Collection object.
Usually we iterate through the entire collection with the For Each...Next Statement.
Each item in a collection can have both a value and a key, where the key is used as the
index to an associated value.
ArrayList Collection
Arraylist is a collection of objects.
If we face trouble and error when working and dealing with the size of the Array
then use ArrayList.
Whereas Arraylist is for Heterogeneous data.The data in the arraylist need not be
of same data type.
255
First object could be a string, second a double, third a user defined object and so
on.
The ArrayList is more dynamic, you can add and remove items without loosing
performance.
Properties of ArrayList
Capacity
Example:
ar.Capacity = 100
End sub
Count
256
Dim ar As New ArrayList
MsgBox(ar.Count) ‗Returns 0
ar.Capacity = 25
Call AddArrayRange()
MsgBox(ar.Count) ‗Returns 5
End Sub
Sub AddArrayRange()
ar.AddRange(str)
End Sub
Item
Example:
Msgbox(ar.Item(0))
Dim i As Integer
For i = 0 To ar.Count - 1
txtPrint.Text &= ar.Item(i) & vbCrLf
Next
End Sub
Methods of ArrayList
Add()
257
It adds the elements in the ArrayList.
Example:
ar.Add("Karna")
ar.Add("Bhavin")
ar.Add("Trivedi")
ar.Add("Vedika")
ar.Add("Shyam")
ar.Add("Chawda")
MsgBox(ar.Count)
End Sub
AddRange
Clear
Example:
Ar.clear()
Contains
GetRange
Example:
ar.Add("a")
ar.Add("b")
ar.Add("c")
ar.Add("d")
ar.Add("e")
258
For Each str In ar
ListBox1.Items.Add(str)
Next
Insert
Example:
ar.Add("a")
ar.Add("b")
ar.Add("e")
InsertRange
Example:
ar.Add("om")
ar.Add("shanti")
ar.Add("om")
strArr(0) = "a"
strArr(1) = "b"
strArr(2) = "c"
strArr(3) = "d" Output
strArr(4) = "e"
ar.InsertRange(2, strArr)
259
Reverse
Example:
ar.Add("a")
ar.Add("b")
ar.Add("c")
ar.Add("d")
ar.Add("e")
ar.Reverse()
Example:
ar.Remove("d")
ar.RemoveAt(2)
ar.RemoveRange(0, 2)
Sort
Example:
ar.Add("Azad")
ar.Add("Suresh")
ar.Add("Anita")
ar.Add("Trupti")
ar.Add("Shanu")
ar.Add("Pooja")
ar.Add("Shweta")
Output 260
ar.Sort()
TrimtoSize
Example:
ar.TrimToSize()
261
Exercise 6
1. Overriadable
2. Overrides
3. Must Override
4. Must Inherit
5. Mybase
6. My class
7. Not inheritable
1. Create order class having product name, price and quantity as properties. Create
one function that calculate total amount. Create constructor and destructor also.
Design the user interface for this class.
2. Extend the above class so that it can calculate total no of orders and sum of total
amount.
3. Class employee having empname, post, eid , salary as properties. Create one
derive class Bonus give bonus to each employee according to their post and
salary and display in the GUI interface. (Eid must be generate automatically)
262
4. Create shape class as abstract class having area () function. Create circle,
triangle, square class based on this shape class . Design user interface for this
class.
263