0% found this document useful (0 votes)
273 views263 pages

1 - ShyamChawadaDotNet - Book

Uploaded by

shobhitdamwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
273 views263 pages

1 - ShyamChawadaDotNet - Book

Uploaded by

shobhitdamwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 263

VB.

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.

 In an event-driven application, the code doesn't follow a predetermined path.

 Everything is depends upon an event.

 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.

Event driven programming is associated with Properties, Methods and Events.

 In daily routine we are using so many objects like TV, Ice-Cream, Bike, Car,
Mobile, Laptop etc.

 Each and every object has properties, methods and events.

 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.

 Properties mean characteristics of anything. Each and every object is identified by


its characeteristics.

 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.

 Given below are the images of events.

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.

 Doing something is method.

 Now we will see the form given below with its properties, events and methods.

Textbox_TextChanged TextBox.Clear()

Textbox Text Textbox_KeyPress TextBox.Cut()

Textbox Font

4
Visual Studio .NET
 Visual Studio .NET is like MS Office.

 Both Visual Studio .NET and MS Office are product of Microsoft.

 MS Office is a package of different types of software. Each software has its own
purpose.

 Visual Studio .NET is complete package of development tools for developing


web applications, desktop applications, mobile applications etc.

 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,

1. Which type of software?


2. In which language?

 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:

1. ASP.NET Web applications(Dynamic website)


2. Windows Form based applications
3. Console applications(DOS base)
4. Smart Device applications (Mobile or PDA base)
5. Class Libraries(Business logic for 3-tier)
6. Web or Windows Custom Controls: (Own windows controls)
7. Web services: They are ―web callable‖ functionality available via industry
standards like HTTP, XML and SOAP.

 Given below are the different version of Visual Studio .NET:

Version Release Visual Studio


Date

1.0 13-2-2002 Visual Studio .NET


1.1 24-4-2003 Visual Studio .NET 2003
2.0 7-11-2005 Visual Studio 2005
3.0 6-11-2006
3.5 19-11-2007 Visual Studio 2008
4.0 10-04-2010 Visial Studio 2010
4.5 09-10-2012

Features of .NET

5
Let‘s see, what makes .NET a wonderful platform for developing modern applications?

Rich set of Classes

 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.

 For example to work with Database we need to include System.Data namespace.

Object Oriented Programming System.

 Visual Studio .NET provides a fully object oriented environment.

 Visual Studio .NET is supports OOPS concepts.

In-built Memory management

 Developers always worry for system resources like memory.

 Visual Studio .NET supports handling memory on its own.

 The garbage collector takes responsibility for free up unused objects for regular
intervals.

Multi-Language and Multi-Device Support

 Visual Studio .NET supports multiple languages.

 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.

 Visual Studio .NET supports Multi-Device.

 We can create Mobile or PDA etc. device supported software.

Faster and easy development of web applications

 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.

Ease of deployment and configuration

 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.

 VB stands for Visual Basic.

 "Visual" part refers to the way used to create the GUI base applications.

 The "Basic" stands for Beginners All-Purpose Symbolic Instruction Code.

 We can create types of applications with the help of VB.NET.

 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

What is the common language runtime (CLR)?


It is the execution engine for .NET Framework applications.

It is the heart or backbone of the .NET.

It‘s is the runtime engine provided by the .NET framework.

It provides an infrastructure for run programs and allows them to communicate with
other parts of the .NET framework.

It provides a number of services, including the following:

 Code loading and execution


 Application memory isolation
 Verification of type safety
 Conversion of IL to native code
 Access to metadata
 Managing memory for managed objects
 Enforcement of code access security
 Exception handling, including cross-language exceptions

What is the common type system (CTS)?


 CTS allow programs written in different programming languages to easily share
information.

 A class written in C# should be equivalent to a class written in VB.NET.

 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.

 It defines rules that a programming language must follow to ensure that


objects written in different programming languages can interact with each other.

 CTS provide cross language integration.

 The common type system supports two general categories of types:

1. Value types
2. Reference types

Value types

 Store directly data on stack. In built data type.

Example: dim a as integer

Reference types

 Store a reference to the value's memory address, and are allocated on the heap.

Example: Dim obj as new Oledbconnection

What is the Common Language Specification (CLS)?


 CLS includes basic language features needed by almost all the applications.

 It serves as a guide for library writers and compiler writers.

 The Common Language Specification is a subset of the common type system.

 The Common Language Specification is also important to application developers


who are writing code that will be used by other developers.

What is an assembly?
 An assembly is the primary building block of a .NET Framework application.

 An Assembly is a logical DLL.

 It consists of DLLs or executables.

 It is a collection of functionality that is built, versioned, and deployed as a single


implementation unit (as one or more files).

All managed types and resources are marked either as accessible only within
their implementation unit or as accessible by code outside that unit.

What are private assemblies and shared assemblies?


 A private assembly is used only by a single application, and is stored in that
application's install directory (or a subdirectory therein).

 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.

 NET records information about compiled classes as Metadata.

 Metadata means data about data.

 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.

 Metadata is nothing but a description of every namespace, class, method,


property etc. contained within the PE file.

The CLR uses this metadata to

• Locate classes
• Load classes
• Generate native code
• Provide security

What is .NET Framework Class Library? (FCL)


 In C, <conio.h>, <stdio.h> etc. are header files. We add those header files in our
program to use inbuilt functions.

 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.

 Other name of FCL is BCL – Base class library.

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.

 Namespace means nothing but a logical container or partition.

 It‘s like Drives of our computer.

 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.

 At the root of the hierarchy is the System namespace.

 The notion of a namespace plays a fundamental role in the .NET Framework.

 For example, In Reliance Industry there is an Executive named Shyam Chawda, a


General Manager named Shyam Chawda, and a Tester named Shyam Chawda.

 In this case, the name Shyam Chawda is ambiguous. (Salary of GM 1,00,000,


Executive 50,000 , Tester 10,000).

 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

System. Diagnostics ,System. Globalization , System. Collections etc.

What is garbage collection? (GC)


 Garbage collection is a mechanism that allows the computer to detect when an
object can no longer be accessed.

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.

 Later we will discuss this topic in destructor.

12
Write down Managed execution process of .NET program
Program execution of VS.NET

Select compiler

Compile code to MSIL

Compile MSIL
MSIL toto
Native with code
Native the help of JIT

Run your code

First step is Select a compiler.

For vb.net select VBC, for C# select CSC same for all language wise select
compiler.

VBC stands for Visual Basic Compiler.

Second step is compile code to Microsoft intermediate language (MSIL) (CIL)


(IL).

Converting your source code into MSIL and generates the metadata.

Third step is compiling MSIL to native code.

JIT compiler translates the MSIL into native code.

Fourth and final step Running code.

The CLR provides the environment that enables execution to take place and
provide other services,

What is the Microsoft Intermediate Language (MSIL)?


 MSIL is the CPU-independent instruction set into which .NET Framework programs
are compiled.

 It contains instructions for loading, storing, initializing, and calling methods on


objects.

 Combined with metadata and the common type system, MSIL allows for true
cross-language integration.

 MSIL also known as CIL – Common Intermediate Language or IL- Intermediate


Language

What is JIT?
13
 It stands for "just-in-time‖.

 It‘s a smart compiler.

 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.

 There are 3 types of JIT

 Pre-JIT – It compiles complete program into native code in a single compilation


cycle. This process is done at the time of deployment of the program.

 Econo-JIT – It compiles only those methods that are called at runtime.

 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

' General Information about an assembly is


controlled through the following
' set of attributes. Change these attribute
values to modify the information
' associated with an assembly.

<Assembly: AssemblyTitle("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>

'The following GUID is for the ID of the typelib


if this project is exposed to COM
<Assembly: Guid("6ACEB232-291B-4EEC-
8462-FEBD203D084B")>

The editor of Assembly file is given here.

What is ILDASM?
 It‘s one kind of software. It is used to view basic information about the project.

 Ildasm.exe can opens any .NET Framework .exe or .dll assembly.

 It displays the MSIL code, namespaces, methods, fields, events, interfaces, etc.

 We can use Ildasm.exe to examine native .NET Framework assemblies.

To open go -> Microsoft Visual Studio 2005 -> Visual Studio Tools -> Visual Studio 2005
Command Prompt -> Type ildasm or ildasm.exe

Then open the file

15
Select any Visual Studio
project -> bin ->debug
folder -> select .exe file

It will display 2 parts: MANIFEST and Project Name


The Manifest shows us all of the "metadata" - such as program dependencies - for our

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.

 We can say Microsoft Word is good due to its IDE.

 Visual Studio.NET provides an environment that‘s common to all languages,


which is known as INTEGRATED DEVELOPMENT ENVIORNMENT.

 It integrates many different functions such as design, editing, compiling, and


debugging within a common environment.

 IDE of Visual Studio.NET as given below image:

Menubar
Toolbar Solution Explorer

Design View

Context Menu

Toolbox Property Window

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

 It is also very common for any software. It contains shortcuts to frequently


performed actions.

 To open a context menu, select any object and click the right mouse button.

 Context menu will open according to object we select.

 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.

 By default Standard toolbar is appear on Visual Studio.NET screen.

 We can add other toolbars from view menu or right click on toolbar itself.

Toolbox (Ctrl + Alt + X)

 Provides a set of controls to place on a form.

 We can also set our own Toolbox, by right click of it.

Solution Explorer (Ctrl + Alt + L)

 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

Property window (F4)

 Lists the properties for the selected control.

 We can use this window to view and change the design-time properties.

Form Designer View (Shift + F7)

 We can drag and drop controls in this view of the form.

 We can also see some type of preview of our form.

Code Editor Window (F7)

 Where we can write the coding of the form or class


etc. like this image.

19
Immediate, Locals, and Watch Windows

 They are used for debugging our application.

 They are only available when we run our application.

 There are two types of Watch window, Add watch and


Quick watch.

Task List (Ctrl + Alt + K)

 To view it select View menu -> Other Windows -> Task List.

 It helps you create and manage a list of programming tasks.

 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.

 Task List displays detected error also.

Command Window (Ctrl + Alt + A)


 To view it select View menu -> Other Windows -> Command Window.

 We can execute both menu commands and commands that do not appear on any
menu.

 The Command window is used to execute commands or aliases.

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.

5. We are going to write coding in button1‟s Click event.

6. Now it‟s time to run the form:


From the menu bar, click Debug -> Start Debugging
Alternatively, press the F5 key on your keyboard
Your program is launched
Then click on Button1, below output will come.

Basic steps to create Application

1. Open Visual Studio.NET


2. Create new Project, Select language Visual Basic
3. Design user interface
4. Write down coding

22
5. Save the Project
6. Test and Debug your application.

23
Exercise 1:
Q1 Answer the following:

1) Explain event, method and property with example.


2) What is event driven programming?
3) What is VS.NET? Explain advantages of it.
4) What is VB.NET?
5) Explain different project type in .net
6) What is IDE? Explain all the IDE of VS.NET.
7) Compare:
VS.NET and VB.NET
Solution and Project
Event Driven Programming and Procedural Oriented Programming.
8) Write down Managed execution process of .NET program
9) What is Namespace?
10) Explain the Import keyword.
11) Exaplin AssemblyInfo.Vb file.
12) Write down properties, methods and events.
a. Nano car
b. Movie
c. Restaurant
d. Mobile

Q.2 Write down full form:

 CLR
 CTS
 MSIL
 IL
 CIL
 JIT
 CLS
 VS.NET
 VB.NET
 IDE
 FCL
 GC

Q.3 Write down short note on:

 .NET Framework
 CLR
 CTS
 CLS
 MSIL
 Managed code and Managed data
 Assembly
 Metadata
 Namespace
 Garbage collection
 JIT

Q.4 Do as directed:

e. JIT converts _______________ into _______________

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.

 Its location and contents determine the variable's characteristics.

Example:

Dim name As String ‗name is String variable


Dim a, b, c As Integer ' All three are Integer variables.
Dim rollno, age As Integer, name As String 'a and b are Integer, name is String

Variable Naming Convention


 Begin with a letter or _.

 Must contain atleaset one numeric digit or alphabetic character with _.

 Maximum 1023 characters.

 Unique in its scope.

Data type
 The data type of a programming element refers to what kind of data it can hold
and how that data is stored.

 There are mainly 3 categories of it.

Numeric Data Types (Short, Integer, Long, Single, Double, Decimal)

Character Data Types (Char, String)

Miscellaneous Data Types (Boolean,Byte, Date, Object)

User-Defined Data Types(Structure, Array , Enum)

Numeric Data Types

Short

 It occupies 2 bytes.

 The range of it -32,768 to 32,767.

26
 Prefix we can use ‗sht‘ and store only whole number

Example: Dim shtRollNo As Short


shtRollNo = 5

Integer

 It occupies 4 bytes.

 The range of it -2,147,483,648 to 2,147,483,647.

 Prefix we can use ‗int‘ and store only whole number

Example: Dim intRollNo As Short


intRollNo = 5

Long

 It occupies 8 bytes.

 The range of it -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

 Prefix we can use ‗lng‘ and store only whole number

Example: Dim lngBankIncome As Long


lngBankIncome = 50000000

Single

 It occupies 4 bytes.

 The range of it -3.4028235E+38 to -1.401298E-45 for negative values;


1.401298E-45 to 3.4028235E+38 for positive values.

 Prefix we can use ‗int‘ and store whole and fractional both

Example: Dim sngSal As Single


sngSal = 5000.5555

Double

 It occupies 8 bytes.

 The range of it -1.79769313486231570E+308 to -4.94065645841246544E-324


for negative values; 4.94065645841246544E-324 to
1.79769313486231570E+308 for positive values.

 Prefix we can use ‗dbl‘ and store whole and fractional both

Example: Dim dblSatyamFraud As Double


dblSatyamFraud = 2222222222222.5557

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

Example: Dim decIncome As Decimal


decIncome = 1.2321334433243232E+19

Character Data Types

Char

 It occupies 2 bytes.

 The range of it 0 to 65535.

 Prefix we can use ‗ch‘ and we need to write (― ―).

Example: Dim chGen As Char


chGen = ―M‖

String

 It occupies 2 bytes.

 The range of it 0 to approximately 2 billion Unicode characters.

 Prefix we can use ‗str‘ and we need to write (― ―).

Example: Dim strAdd As String


strAdd = ―B-F/1, Rajvi Complex, Gurukul Road, Memnagar‖

Miscellaneous Data Types

Boolean

 It occupies 2 bytes.

 It can store either ―True‖ or ―False‖

 Prefix we can use ‗bln‘

Example: Dim blnGen As Boolean


blnGen = True

Byte

 It occupies 1 byte.

 The range of it 0 to 255.

28
 Prefix we can use ‗byt‘
 Usually Byte data type is used to access binary files, image and sound files etc.

Example: Dim bytNo As Byte


bytNo = 223

Date

 It occupies 8 bytes.

 Minimum value is 0:00:00 on January 1, 0001 and Maximum value 11:59:59 PM


on December 31, 9999.

 Prefix we can use ‗dt‘ and we need to write (# #)

 The format of Date variable is #mm/dd/yyyy#

Example: Dim dtDob As Date


dtDob = #12/21/1982#

Object

 It occupies 4 bytes.

 It can store any type of data. Prefix we can use ‗obj‘.

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.

But when we create Dim A As Object=5

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.

User-Defined Data Types

We will see this topic later.

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:

0 for all Numeric types and Byte.

Binary 0 for Char.

Nothing for all reference types like Object, String, and Arrays etc.

False for Boolean.

12:00 AM of 1,1,0001 for Date

We can initialize the variable by 2 ways as below example:

1. Dim name As String ="Shyam"

2. Dim name As String


name = "Shyam"

Example: Take user input in the Textbox control and print in another textbox
control.

Step 1: Design form properly

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.

Step 3: Write down coding on Command button‘s click event

Now double click on btnAns 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

Private Sub btnAns_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnAns.Click

txtAns.Text = txtName.Text

End Sub

Step 4: Run your program

Form

When we click on btnAns control, that time event will raise and task is transfer data from
one control to another.

It‘s same like transferring data from one variable to another.

Example:

Dim intA, intB As Integer

intA=10 ‗10 will copy into intA

intB=intA ‗intA‘s data will copy into intB

Same as above txtAns.Text = txtName.Text. Because the is value stored in the


Text property of the Textbox control we have to write .Text

Example 2: Addition of Textbox controls and print answer in Label control.

txtNo1 Write down coding in btnAns_click

lblAns.Text = txtNo1.Text + txtNo2.Text


txtNo2

btnAns

32
lblAns
But answer is wrong. Why? Remember that Textbox always return String value.

“20” means string

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.

So we need to use Type conversion function.

And finally our coding is like

Function name
Argument Return type

Coding Window

Coding : lblAns.Text = CInt(txtNo1.Text) + CInt(txtNo2.Text)

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.

 There are 2 type of conversion: Implicit and Explicit.

 An implicit conversion does not require any special syntax in the source code.

 An explicit conversion requires function.

 In the following example, VB.NET converts the value of A to B.

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.

Function name Converts into


CBool Boolean
CByte Byte
CChar Char
CDate Date
CDbl or Val Double
CDec Decimal
CInt Integer
CLng Long
CObj Object
CShort Short
CSng Single
CStr String

Syntax: Function Name (argument)

Example:

Dim str As String Dim str As String


Dim no As Integer Dim dt As Date

str = "5" str = "12/21/1982"


no = CInt(str) dt = CDate(str)

34
CTYPE Function

 It uses to convert one type to another type.

 Instead of rember all conversion functions, rember only CTYPE function.

Syntax: Ctype (expression, Type name)

Example:

Dim no1 As Integer


Dim no2 As Double

no2 = 66.77

no1 = CType (no2, Integer)

MsgBox (no1)

 Execution is faster because there is no call to a procedure to accomplish the


conversion.

Boxing and Unboxing

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

The conversion of a value type instance to an object,

Unboxing

The conversion of an object instance to a value type.

Example

Dim no As Integer=10

Dim obj As Object = no ' boxing

Dim ans As Integer = CInt(o) ' unboxing

35
Type Checking Functions
VB.NET provides number of data verification or data type checking functions as below:

 IsDate
 IsNothing
 IsNumeric
 IsDBNull
 IsArray

IsDate

 Returns True or False.

Example:

Dim dt1, dt2 As Date


Dim strTemp As String
Dim bolAns As Boolean

dt1 = "February 17, 2007"


dt2 = #1/17/1982#
strTemp = "India is great"

bolAns = IsDate(dt1) ' Returns True.


MsgBox(bolAns)
bolAns = IsDate(dt2) ' Returns True.
MsgBox(bolAns)
bolAns = IsDate(strTemp) ' Returns False.
MsgBox(bolAns)

IsNothing

 Returns True if the Object variable that currently has no assigned value;
otherwise, it returns False.

Example:

Dim objTemp As Object ' No instance assigned to this variable yet.


Dim bolAns As Boolean

bolAns = IsNothing(objTemp) ' Returns True.


MsgBox(bolAns)

objTemp = "Dolly" ' Assign a string instance to the variable.


bolAns = IsNothing(objTemp) ' Returns False.
MsgBox(bolAns)

objTemp = Nothing ' Assing Nothing means write now no value


bolAns = IsNothing(objTemp) 'Returns True.
MsgBox(bolAns)

IsNumeric

 Returns True if the value is numeric; otherwise, it returns False.

36
Example:

Dim objTemp As Object


Dim str As String
Dim bolAns As Boolean

objTemp = "53"
bolAns = IsNumeric(objTemp) ' Returns True.
MsgBox(bolAns)

str = "459.95"
bolAns = IsNumeric(str) ' Returns True.
MsgBox(bolAns)

objTemp = "45 Help"


bolAns = IsNumeric(objTemp) ' Returns False.
MsgBox(bolAns)

IsDBNull

 IsDBNull returns True if the value evaluates to the DBNull type; otherwise,
returns False.

 The System.DBNull value indicates that the Object represents missing or


nonexistent data.

 DBNull is not the same as Nothing or null string.

Example:

Dim objTemp As Object


Dim bolAns As Boolean

bolAns = IsDBNull(objTemp) ' Returns False.


MsgBox(bolAns)

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

Purpose: Force explicit declaration of all variables in program.

Value: On / Off

Default: On

 It is not compulsory to write Option Explicit option.

 If used, the Option Explicit statement must appear in a file before any
statements.

 It is used to avoid incorrect typing the name and avoid confusion.

 We can reduce the possible errors that result from misspelled variable names.

 Because in Option Explicit On mode we have to declare each variable in the


program for storing data, otherwise it will display error at compile time.

 If we don't declare variable before it used, all undeclared variables are of Object
type.

Example

The error is due to default Option explicit


is On.

We should declare variable before it is


used.

Now,

Error is gone. Due to setting Option Explicit


has turned Off.

So, if we do not want to declare variable


then set option explicit off.

Option Strict

Purpose: Restricts implicit data type conversions widening to narrowing conversions

Value: On / Off

Default: Off

 If used, the Option Explicit statement must appear in a file before any
statements.

 VB .NET allows implicit conversions from one type to other type.

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.

 Option Strict ensures compile-time notification of this improper conversion


otherwise; a run-time error message will occur if data will be lost in such a
conversion.

 Option Struct prevents program from automatic variable conversions.

Example

Data can loss in this coding, but there will


be no error display.

Because Option Strict Off by default.

Now,

Set Option Strict On

Run project

Error will display.

So, if we want to display error compile


time for type conversion, then use
Option Strict concept.

Coding Window

We can set both options by Tools Menu -> Option -> Projects and Solutions

39
Operators
 An operator is a symbol or character.

 It allows us to manipulate data. An operator performs a function on one or more


operands.

Example:
Dim Ans As Integer

Ans=2+5

Here 2 and 5 are operands and + is an operator.

 Operators that take one operand are called unary operators.

 Operators that take two operands are called binary operators.

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 &, +

Assignment =, ^=, *=, /=, \=, +=, -=, &=

Comparison/Relational =, <>, <, >, <=, >=, Like, Is

Logical/bitwise Not, And, Or, Xor, AndAlso, OrElse


operations
Miscellaneous operations GetType

40
Arithmetic Operators

Perform the standard arithmetic operations on numeric values.

 * Multiplication

 + Addition

 - Subtraction

 / Regular division

Example:

Dim no1 As Integer = 20


Dim no2 As Integer = 3

MsgBox(no1 / no2) ' Display 6.6666667

 \ Integer division – Display nearest integer value.

Example:

Dim no1 As Integer = 20


Dim no2 As Integer = 3

MsgBox(no1 \ no2) ' Display 6

 Mod (Modulo) – Display remainder of division

Example:

Dim no1 As Integer = 20


Dim no2 As Integer = 3

MsgBox(no1 mod no2) ' Display 2

 ^ Exponentiation - first operand raised to the power of the second


operand.

Example:
Dim no1 As Integer = 5
Dim no2 As Integer = 3
Dim ans As Integer

ans = no1 ^ no2 ' Stores 125 into ans variable.

41
Example: Create simple calculator using 2 textboxes and 1 label for answer.
Take 5 buttons for perform +,-,X,\ and Clear the values.

We set name of the 1st textbox txtNo1, name of the


second textbox is txtNo2,

Private Sub btnAdd_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnAdd.Click

lblAns.Text = Val(txtNo1.Text) + Val(txtNo2.Text)

End Sub

Private Sub btnSub_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnSub.Click

lblAns.Text = txtNo1.Text - txtNo2.Text


Output
End Sub

Private Sub btnMul_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnMul.Click

lblAns.Text = txtNo1.Text * txtNo2.Text

End Sub

Private Sub btnDiv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnDiv.Click

lblAns.Text = txtNo1.Text / txtNo2.Text

End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click

lblAns.Text = ""
txtNo1.Clear()
txtNo2.Clear()

End Sub

Concatenation Operators

 The & (ampersand) and + (plus) characters is used for string


concatenation.

Example:

Dim str As String

str = "India is great"

MsgBox(str)

str &= " I love my India"

42
MsgBox(str)

Str &=” I am Indian” & ― I am proud to be an Indian‖

MsgBox(“Hai “ & str)

 We can write either Str &=‖ I love my India‖ (shortHand) or Str =Str & ‖ I love
my India‖

 We can also use + operator as a concatenation operator.

Example:

Dim ans As String

ans = "Abhishek" + "Bachhan" ‗ String concatenation


MsgBox(ans)

ans = 5 + 7 ‗ Arithmetic addition


MsgBox(ans)

Assignment Operators

 They carry out assignment operations.

 = is commonly used Assignment operator.

 ^=, *=, /=, \=, +=, -=, &= are also known as Shorthand operators.

Example:

Dim No As Integer

No = 15 ‗= operator is used Assign 15 to No variable.

No -= 2 ‗ -=

MsgBox(No)

Relational/Comparison Operators

They perform some comparison between two operands and return a Boolean value.

= Equality

In C or C++ if we wants to compare 2 value then we have to use == operator.

But in VB.NET we can use = operator.

Like + operator can work as a Concatenation or Arithmetic operator, = operator can


work as an Assignment or Relational operator. With If..else block = operator work as a
Relational operator. It compares value.

43
Example:

Dim no As Integer

no = 10 ‗Here = operator work as an Assignment operator

If no = 20 Then ‗Here compares value


MsgBox("No is 20")
Else
MsgBox("No is not 20")
End If

<> Not Equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

TypeOf...Is

 The TypeOf...Is operator is checked first parameter and with the type as its
second parameter.

 Use the TypeOf...Is operator to determine whether a given object Is an object of


a given class.

Example:

Dim btn As New Button


btn.Text = "Hai"
Me.Controls.Add(btn)

If TypeOf btn Is Button Then

MsgBox("Yes this is button")

End If
IS

 The Is operator determines whether two object reference variables refer to the
same object instance.

Example:

Dim tmp1, tmp2 As Object

If tmp1 Is tmp2 Then


MsgBox("Both are same type")
Else
MsgBox("No")
End If

44
Like

 The Like operator can work only with operands of type String and
Character.

 It compares a string to a pattern.

Syntax: Operand Like Pattern

Example:

Dim bolAns As Boolean

bolAns = "S" Like "s" ‗Returns False

MsgBox(bolAns)

bolAns = "S" Like "S" ‗Returns True

MsgBox(bolAns)

bolAns = "S" Like "SSS" ‗Returns False

MsgBox(bolAns)

We can also use below characters in pattern.

Characters in pattern Matches in string


? Any single character
* Zero or more characters means any
Alphanumeric or symbols
# Any single digit (0–9)
[charlist] Any single character in charlist means in
between
Example: [A-C] , [D-M]
[!charlist] Any single character not in charlist means
not in between
Example: [!A-C] , [!D-M]

Example:

bolAns = "Ritu" Like "R*u" ‗Returns True

MsgBox(bolAns)

Example:

bolAns = "R" Like "[A-Z]" ‗Returns True, means between A….Z

MsgBox(bolAns)

Example:

45
bolAns = "R" Like "[!A-C]" ‗Returns True , means not between A,B,C

MsgBox(bolAns)

Example:

bolAns = "R2R" Like "R#R" ‗Returns True

MsgBox(bolAns)

Example:

bolAns = "aM5a2" Like "a[B-T]#?#" ‗Returns True

MsgBox(bolAns)

Bitwise/Logical Operators

 The logical operators compare Boolean expressions and return a Boolean result.

And

 Both conditions must be true then follows the logic.

Example:

Dim no1, no2 As Integer

no1 = 10
no2 = 20

If no1 > 5 And no2 > 10 Then


MsgBox("Both condition is satisfied")
Else
MsgBox("Not match")
End If

46
Or

 If one of the conditions is true then return true and follows the logic.

Example:

Dim no1, no2 As Integer

no1 = 10
no2 = 20

If no1 > 5 Or no2 < 10 Then ‗Check the output


MsgBox("Match")
Else
MsgBox("Not match")
End If

AndAlso and OrElse are like And and Or except that they will "short circuit".

AndAlso

 AndAlso performs logical short-circuiting: if the first operand of the expression is


False, the second operand is not evaluated.

 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.

 We cannot feel the speed. So, don‘t check that thing.

 AndAlso = If first one condition is True then and then check second one condition.

 AndAlso = And+Also

 AndAlso = Compulsory both must be True.

Example:

Dim no1, no2 As Integer

no1 = 10
no2 = 20

If no1 < 5 AndAlso no2 > 10 Then ‗Check the output


MsgBox("Match")
Else
MsgBox("Not match")
End If

 In above example, first condition is False so AndAlso operator doesn‘t waste time
to check second one.

47
OrElse

 OrElse performs logical short-circuiting: if the first operand of the expression is


True, the second operand is not evaluated.

 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.

 We cannot feel the speed. So, don‘t check that thing.

 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

 OrElse =Either + Or condition is True.

Example:

Dim no1, no2 As Integer

no1 = 10
no2 = 20

If no1 > 5 OrElse no2 < 10 Then


MsgBox("Match")
Else
MsgBox("Not match")
End If

 In above example, first condition is True so OrElse operator doesn‘t waste time to
check second one.

Xor

 Performs a Boolean exclusive or operation on the bits.

 It follows below conditions display in table to return True or False.

If expression1 is And expression2 is The value of result is


True True False
True False True
False True True
False False False

Example:

Dim xorValue As Boolean


Dim a As Integer = 30
Dim b As Integer = 7

48
Dim c As Integer = 2

xorValue = a = 30 Xor b = 7 'False


MsgBox(xorValue)

xorValue = b > a Xor c > b 'False


MsgBox(xorValue)

xorValue = a > b Xor b > c 'False


MsgBox(xorValue)

xorValue = b > a Xor b > c 'True


MsgBox(xorValue)

Not

 Performs a Boolean Not operation on the bits in the operand. This is a unary
operator.

Example:

Dim a As Integer = 5

If Not a > 5 Then


MsgBox("Yes a is not max then 5")
Else
MsgBox("No a is not max then 5")
End If

Miscellaneous Operators

GetType

 Returns a Type object for the specified type.

 The GetType operator returns a System.Type object that contains information


about the data type of the operand.

 It retrieves information about the type of object , variable , properties, methods,


and events etc.

Syntax: GetType(typename)

Example

Dim a As Integer = 5

Dim btn As New Button

MsgBox(a.GetType().ToString)

MsgBox(btn.GetType().ToString)

49
Write down in memory.

IF we wants to multiple statement in one line then use ―:‖

Example:

Dim str1 As String

str1 = "India" : MsgBox(―I love my ‖ & str)

If we wants to write one statement on multiple lines ( _ ) like we write _ in our


notebook.

Dim strName As String

strName = "Mr." & " " & "Karna" & _


" Bhavin" & _
" Trivedi"

MsgBox(strName)

To declare Constant variable use Const keyword.

Example: Const PI As Long = 3.144456677

Shared variable are global for all the events and procedures.

Example: Shared op As Boolean

Follows the Prefix for variables and controls it‘s a habit of a good programmer.

Check below coding practically:

Dim no1 As Integer=10

lblAns.Text =no1 & ― is even‖

Run your project. After this, remove the above line and write below the line and
run your project and compare output.

lblAns.Text = ―no1 is even‖

50
We can add multiple forms in a project, so don‘t create New project for each and every
time.

Right click of the Solution Explorer

Project Menu -> Add Windows Form

Give proper name like frmOddEven , frmPrime etc.


to our form so, If our project contains 200 forms
even though we can identify each and every form
by its name.

We want to run other form from our project when we press F5 then it makes them as a
Startup form as given below:

We can open this window by

 Right click -> Solution Explorer ->

 Project Menu ->

51
What is comment?
 Comments are optional part of coding.

 It displays at design time.

 It‘s very important for any software.

 It never compiles. VB ignore whatever statements follows the in the comment

 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.

There are 3 ways to comment

1. Using ‗ (Single quote)

2. Using Rem: keyword (Remark)

3. Using Toolbar Icon

Toolbar

Comment out the selected line

UnComment the selected line


Example: Using (‗)

Example: Using REM:

Example: Using Toolbar options

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.

Setting the Password char property to * design time

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.

 Control statements enable us to execute a certain set of statements based on a


condition.

 The condition is evaluated runtime and depending on the result of condition, the
block of code will execute.

 Control Structure also known as Branching statements or Test Structure or


Decision Structure.

 Control Structure includes:

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.

 The condition usually results from a comparison of two values.

 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.

 We can have any number of ElseIf statements or none.

 We cam use If..Then..Else block to evaluate more than one condition.

 We can also write nested If..Then..Else block.

 Then keyword is used with If.. and ElseIf.. Statements.

Syntax:

If condition Then
Logic..
ElseIf condition-n Then
Logic…
Else
Logic…
End If

54
Example: Single If block

Private Sub btnAns_Click

If IsNumeric(txtNo.Text) Then

lblAns.Text = ("Yes data is numeric")

End If

End Sub Form

Example: If..Else block

Private Sub btnAns_Click()

If txtNo.Text Mod 2 = 0 Then

lblAns.Text = "No is even"

Else

lblAns.Text = "No is odd"

End If Form

End Sub

Example: If..ElseIf..Else block

Private Sub btnAns_Click()

Dim no1, no2 As Integer

REM: Transfers data from textboxes to vairables

no1 = txtNo1.Text
no2 = txtNo2.Text

If no1 > no2 Then


lblAns.Text = no1 & " is max"
ElseIf no2 > no1 Then
lblAns.Text = no2 & " is max"
Else Form
lblAns.Text = "Both are same"
End If
End Sub

 We can also use logical operators in If..Then..Else block like below:

Example:

If a>b AndAlso b>c then


Logic…
ElseIf a>b or b>c then
Logic…

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 executes one of several groups of statements depending on the value of an


expression.

 If..Then..Else block executes different condition or expression in each statement,


the Select statement evaluates a single expression and compares it for every
comparison.

 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.

 If..Then..Else block are time consuming then Select case 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 use the To keyword to specify a range of values.

 We can also use Is keyword. The Is keyword is used with any comparison
operators.

 We can use nested Select case block also.

Syntax:

Select Case testexpression

Case expressionlist-n
Logic ...
Case Else
Logic ...

End Select

Example:

56
Private Sub btnAns_Click()

Dim age As Integer = txtAge.Text

Select Case age

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

 The For loop executes a block of statements a specified number of times.

 It‘s most commonly and most popular loop used in any programming language.

 Rember Next keyword should be used in For…Next at the end.

Syntax:

For counter = start To end [Step increment/decrement]


Logic…
Next

Examples:

Dim I as Integer Dim I as Integer Dim I as Integer

For I = 0 To 10 Step 1 For I = 0 To 10 For I = 50 To 1 Step -2


Logic… Logic… Logic…
Next Next Next

Dim I as Integer Dim I,J as Integer Dim I,J,K as Integer

For I = 1 To 100 Step 2 For I = 1 To 50 For I = 1 To 50


Logic… For J = 1 To 30 For J = 1 To 30
Next Logic.. For K = 1 To 10
Next J,I
Logic..
Next Next Next

 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.

 We can set increment or decrement by Step keyword.

 Step keyword is optionally to write.

58
 The step value can be positive to increment and negative to decrement the
counter.

 By default loop will incremented by 1.

Example: Print 1 to 10 in Textbox using For..loop When form is Load

(New event Form_Load for this double click on the form)

Private Sub frmLoop_Load()

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.

Private Sub frmLoop_Load()

Dim i As Integer

For i = 0 To 10

txtAns.Text &= i & space(2)

Next Form

End Sub

Space function

Space(value) is the function which gives spaces according to we pass value.

Example: Space(5) then give us 5 spaces

vbNewLine , vbCrLf Constants

Both are used for New line like ‗\n‘ effect in C or C++.

We can also use chr(13) + chr(10) for New line.

Check this practically vbTab , chr(9) ,vbBack ,chr(8),chr(34)

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

txtAns.Text &= i & vbNewLine

Next

Property Window Form

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.

 In While loop programmer have to maintain or kepp track of increment or


decrement value.

Syntax
While condition
Logic..
End While

Example: Display number from 5 to 1

Dim no As Integer = 5

While no > 0

Msgbox(no)

no = no – 1

End While

60
Do… Loop

 Repeats a block of statements while a Boolean condition is FALSE or until the


condition becomes TRUE.

Syntax

Do { While | Until } condition


Logic…
Loop

-or-

Do
Logic..,
Loop { While | Until } condition

We can use either While or Until

While
Repeat the loop until condition is FALSE.

Until
Repeat the loop until condition is TRUE.

Example: Find factorial of 5

Dim no As Integer = 5 Dim no As Integer = 5


Dim ans As Integer = 1 Dim ans As Integer = 1

Do Until no >= 1 Do While no >=1


ans = ans * no ans = ans * no
no = no - 1 no = no - 1
Loop Loop

MsgBox("Factorial of 5 is " & ans) MsgBox("Factorial of 5 is " & ans)

Will work. No>=1 true so it will


Wil not work. No>=1 is False so
run.
it will not work.

Change Do Until no <= 1 and now


run the program.

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.

 Repeats a group of statements for each element in a collection.

 We will learn more about collection and arrays in the later topics.

Syntax

For Each element In group


Logic..
Next

Example: Print Array data using For each loop

Dim noArr(2), temp As Integer

noArr(0) = 11
noArr(1) = 22
noArr(2) = 33

For Each temp In noArr

MsgBox(temp)

Next

Example: Count number of textboxes on form.

Private Sub btnCount_Click()

Dim ctl As New Control

Dim cnt As Integer

For Each ctl In Me.Controls

If TypeOf ctl Is TextBox Then


cnt = cnt + 1
End If

Next

MsgBox(cnt)
Form
End Sub

Me.Controls is the collection of controls appear in the current form.

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.

 Remember this is not a type of Loop.

Syntax

With object Name


Logic…
End With

Example: Sets some properties of a Mobile.

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

So, there is no need to write Mobile keyword four times.

Example:With..End with block using btnAns

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 keyword is used for refer current form.

 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:

.vbproj->A Visual Basic project

Form1.vb->A form's code

AssemblyInfo.VB->Information about an assembly, includes version information

.vbproj.user->Stores project user options

.sln->Solution file which stores solution's configuration

.suo-> Stores Solution user options

Form1.resx.NET->XML based resource template

bin directory->Directory for binary executables

obj directory->Directory for debugging binaries

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 and Inputbox both are inbuilt functions.

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.

MsgBox is the Modal dialogbox.

Prompt is the compulosary argument of it, Style and Title arguments are optional.

By default it sets Title = project name.

Example:

MsgBox("Hai")

Example:

MsgBox("Welcome", , "Message to user")

Some of the values of argument style as given below:

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.

A message box can display with various icon and button.

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:

Dim ans As Integer

ans = MsgBox("Can you give me answer?", MsgBoxStyle.Information +


MsgBoxStyle.YesNoCancel, "Hai")

If ans = 6 Then ‗Yes button


MsgBox("Thanks")
ElseIf ans = 7 Then ‗No button
MsgBox("Why no?")
ElseIf ans = 2 Then ‗Cancel button
MsgBox("Why cancel?")
End If

MessageBox.Show

 It‘s an advance version of MsgBox function.

 MessageBox is the class and Show is the method of it.

 Show method has more arguments then MsgBox function.It contains separate
arguments for icon and button.

 It also provides alignment option, helpbutton and default button options.

Syntax:

MessageBox.Show(Text,caption,button,icon,default button,options,help button)

Example:

MessageBox.Show("Welcome", "Demo", MessageBoxButtons.YesNo,


MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign, True)

66
InputBox

 The InputBox function is to accept data from the user.

 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:

ans=InputBox(Prompt, Title, default_text, x-position, y-position)

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.

Dim ans As String

ans = InputBox("Enter name", "Info", "here")

MsgBox(ans, , "Ans")

Example: Take 2 values from the user and find the maximum between them.

Dim no1, no2 As Integer

no1 = InputBox("Enter no1")


no2 = InputBox("Enter no2")

If no1 > no2 Then


MsgBox("no1 is max")
Else
MsgBox("no2 is max")
End If

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.

 We can divide the big program into small procedures.

 Due to Procedure the applicaton is easier to debug and easier to find error.

 Resuablity of procedure is the one of the great advantage of it.

 Procedure have 2 categoreis In-built or User-defined procedures.

There are 4 types of Procedures in VB.Net

 Sub procedures does not return value

 Event-handling procedures are Sub procedures that execute in response to an


event triggered by user action. Like button1_Click

 Function procedures return a value.

 Property procedures used in object oriented concept.

Modular Coding
There are 2 approaches for doing modular coding in VB.net

1. Sub Routines or Sub Procedure


2. Function Procedure

The main concept is breaking large application into smaller.

If your procedure does not return any value then it should be implemented as a sub
procedure else function.

The approach of modular coding is dividing-conquer approach.

Procedure1 starts

Logic...
Procedure2 (para1, para2)
Logic…

Procedure1 ends

Procedure2 starts(P1 as <type>, P2 as <type>)

Logic..

Procedure1 ends

68
Sub Procedures

 A sub procedure is nothing more than a small block of program in itself.

 It is also known as Sub Routine.

 There are 2 parts of it declaring and calling.

 We should give proper name to it throught which we can rember it easily.

 Sub procedure may or may not have arguments. Arguments are not
compulsory.

 Sub procedure does not return the value.

 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:

[accessibility] Sub subname (argumentlist)

Logic…

End Sub

 The accessibility can be Public, Protected, Friend, Protected Friend, or Private.

 By default accessibility is Public.

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.

Change our Sub procedure and write down below coding:

Example: With argument Sub procedure.

Sub Hai(ByVal str As String)

MsgBox("Hello how are u?" & str)

End Sub

69
Coding Window

Our Subroutine Explanation

Now go to btnAns_click event and type Call Hai and we can see the magic as above
image will display.

Calling syntax:

Call Hai(txtName.Text) or Call Hai(“Shyam”) because it requires string as an


argument.

Examples: Some of the examples of Sub procedure are given below:

Sub add(ByVal a As Integer, ByVal b As Integer) Sub Clear()

Msgbox(―Ans = ― & (a+b)) txtAns.clear()


txtNo1.clear()
End Sub
End Sub

Sub IsOdd(ByVal a As Integer) Sub PrintTable(ByVal a As Integer)

Logic.. Logic..

End Sub End Sub

70
Function

 A Function procedure is similar to a Sub procedure, but it returns a value to


the calling program.

 Function procedure may or may not have arguments.

 Here statements enclosed by the Function and End Function.

 ByVal is by default argument type.

 As clause is writtern after the parameter list is set.

 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.

 By default functions are public.

Syntax

[accessibility] Function functionname[(argumentlist)] As Returndatatype

Logic….

[Return value]

End Function

Example: Create Square function which takes one argument and returns square
of that argument.

Function Square(ByVal No As Integer) As Integer

Return No * No

End Function

Now call the function

Form

Coding Window

Our Function

Name Argument Return type


71
Calling syntax:

lblAns.Text = Square(txtNo.Text)
or
lblAns.Text = Square(5)

Examples: Some of the examples of Function procedure as given below:

Function add(ByVal a As Integer, ByVal b As Integer) As Integer

Return a+b

End Sub

Sub IsEven(ByVal a As Integer) As Boolean

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.

 In C++ this concept is known as default argument.

 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

Some rules of the optional argument

 Rember that if we make one argument optional, all the following arguments must
be optional.

 We must specify a default value for every optional argument.

Syntax

Sub subProcName(para1 as <type>,optional para2 as <type>=value)

End Sub

Function funcName(para1 as <type>,optional para2 as <type>=value)as <type>

End Function

Example: Create Add subprocedure which contains one of the argument is optional.

Sub add(ByVal no1 As Integer, Optional ByVal no2 As Integer = 0)

MsgBox(no1 + no2)

End Sub

Now we are going to call in the btnAns_Click event

[ ] brackets are identifying


optional argument and also
see the default value 0

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.

Sub prData (Optional ByVal ch As Char = "v", Optional ByVal no As Integer = 5)

Dim i As Integer

For i = 0 To no
txtName.Text &= ch & vbCrLf
Next

End Sub

Calling syntax:

Call printData("a", 5) ‗ Both default value is overriten ch=‖v‖ and no=5

Call printData("d") ‗ch=‖d‖ and no=5 only ch parameter is passed

Call printData() ‗ch=‖v‖ and no=5 default arguments

Call printData(, 10) ‗ch=‖v‖ and no=10 only no parameter is passed

Example: Create multiplication function which has 3 arguments and 1 of them


is optional argument.

Function mul(ByVal a As Integer,Optional ByVal b As Integer=10, ByVal c As Integer)


As Integer

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.

It means if we have 5 arguments and if we want to make 3 of them as an


optional then declare last 3 arguments are an optional.

Rewrite again above function make it correct.

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.

 In VB.NET we can declare 2 or more procedures with same name.

 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.

 The programmer‟s view function overloading is a convenient way of


providing multiple variations on the same theme.

 An inbuilt function also uses this


concept. 1 of 2 is mention means 2
functions with the same name and we
currently select one of them.

Example: Create 4 add() functions that show the demo of function overloading.

Sub add()

Logic..

End Sub

Sub add(ByVal no As Integer)

Logic..

End Sub

Sub add(ByVal no1 As Integer, ByVal no2 As Integer)

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.

 The word ByVal is short for "By Value".

 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.

 By default, ByVal is used in VB.NET procedures.

 ByRef is the short form of ―By Reference‖.

 ByRef refers to actual argument itself is passed. The memory-address itself is


passed.

 In ByRef both the variable and the argument refer to the same memory location
hence the ByRef keyword.

 It is depends on requirement to use ByRef instead of ByVal. We pass arguments


by reference only if the procedure has reason to change its value.

 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.

Example: Swapping of 2 values

Private Sub btnAns_Click()

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)

Dim temp 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.

Sub Swap(ByRef a As Integer, ByRef b As Integer)

Dim temp As Integer


temp = a
a=b
b = temp

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.

There are 3 ways to pass arguments as below:

1. Passing Arguments by Position (Ordered argument)


2. Passing Arguments by Name
3. Mixing Arguments by Position and by Name

Passing Arguments by Position.

 This method is common for every programming language.

Example: By Position

Sub StuInfo(ByVal name As String, ByVal rollno As Single)

Logic…
End Sub

Calling Syntax: Call StuInfo("Reva", 5)

We can say above passing or calling procedure to Passing Arguments by Position.

Passing Arguments by Name

 We can call StuInfo with the arguments passed by name.

 We should use variable name and ―:‖.

Example: Call above StuInfo procedure using By Name

Calling Syntax: Call StuInfo(Rollno:=5, Name:="Reva")

Mixing Arguments by Position and by Name

 Mix mode of both above. If we supply arguments both by position and by name,
the positional arguments must all come first.

 Once we supply an argument by name, the remaining arguments must all be by


name.

Example:

Sub Addimision(ByVal name As String, ByVal total As Single, ByVal fdate As Date)

End Sub

Calling Syntax: Call Addimision("Ankit", fdate:=#5/5/2009#, total:=200)

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

 In event handler is a method that is bound to an event.

 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.

 Event handler never returns the value.

Example:

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAns.Click

Logic…

‗Here btnAns.Click handel or raise this logic


End sub

Private Sub frmDemo_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Logic…

‗Here form‘s Load event will handel

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.

 Sender perform same task for all the event.

 The “e” is depends on event.The properties of e object is vary from event to


event.

Example: Take 3 textboxes and one command button, assign button name property to
btnAns

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

TextBox1.Text = (sender.GetType.ToString) 'System.Windows.Forms.Button

TextBox2.Text = (sender.Name) ‗stores btnAns

TextBox3.Text = (sender.Text) 'stroes Answer

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.

Private Sub frmForm_Op_Closing(ByVal sender As Object, ByVal e As


System.ComponentModel.CancelEventArgs) Handles MyBase.Closing

Dim bol As Single

bol = MsgBox("Do u want to close ? ", MsgBoxStyle.Critical + MsgBoxStyle.OKCancel,


"Closing")
If bol = 1 Then
e.Cancel = False
Else
e.Cancel = True
End If

End Sub

Example: Only numeric data should enter in the textbox.

Private Sub txtNo2_KeyPress(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyPressEventArgs) Handles txtNo2.KeyPress

If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 8 Then


e.Handled = False
Else
e.Handled = True
End If
End Sub

We can also use the same event handler to handle the same event for different
controls.

In VB 6.0 there is a concept of Control Array (Not possible in VB.NET), control


arrays could be used to specify a group of controls that shared a set of events.

We can implement Control Array concept here by making common handler.

For example, if we have a group of Textbox or RadioButton or any controls on a form,


we could create a single event handler for the Click event and have each control's Click
event bound to the single event handler.

Example: Two textboxes and common event handler

Private Sub txtNo1_KeyPress(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyPressEventArgs) Handles
txtNo1.KeyPress, txtNo2.KeyPress

If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 8 Then


e.Handled = False
Else
e.Handled = True

82
End If
End Sub

Example: Create simple calculator using the concept of Sender.

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.

Create group of 0 to 9 and second group of Operator buttons.

Public Class frmCalci

Dim no1 As Double


Dim op As Char

Private Sub btn0_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click,
btn6.Click, btn7.Click, btn8.Click, btn9.Click

txtAns.Text &= sender.text

End Sub

Private Sub btnDiv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnDiv.Click, btnMin.Click, btnMul.Click, btnPlus.Click

no1 = txtAns.Text
txtAns.Clear()
op = sender.text

End Sub

Private Sub btnEqual_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnEqual.Click

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

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click

txtAns.Clear()

End Sub
End Class

84
Exit
 The Exit statement stops execution and jump to that part of the block.

 It‘s like break statement of C and C++.

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

Example: Prime number

Private Sub btnAns_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnAns.Click

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

If flag = True Then


lblAns.Text = "No is Not prime"
Else
lblAns.Text = "No is prime"
End If

End Sub

85
String Class’s Properties and Method.
Length

 It‘s a property not a function.

 It returns the length of the string.

 Len() is function also. We can use any of this 2 options to check length of the
string.

Example:

str = "Yash and Karna are good boys."

ans = str.Length() ‗ans=Len(str)

Functions

Compare

 It‘s use for comparing 2 strings.

Example:

Int_Compare = str.Compare("abc", "ABC", True)

MsgBox(Int_Compare, MsgBoxStyle.Information, "Comparison")

Int_Compare = str.Compare("ABC", "abc")

MsgBox(Int_Compare, MsgBoxStyle.Information, "Comparison")

Int_Compare = str.Compare("ABC", "ABC")

MsgBox(Int_Compare, MsgBoxStyle.Information, "Comparison")

Output of 1st is 0 ,2nd –1,3rd is 0.

Concat

 Combined 2 strings. Places them one after the other and forms a new string.

 We can use &,+ operators also instead of this.

Example:

str1 = "My name is Shyam N. Chawda. "


str2 = "My contact no is 9374928879"

str1 = String.Concat(str1, str2)


MsgBox(str1)

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:

str1 = "My name is Shyam N. Chawda. "


str2 = "My contact no is 9374928879"

str2 = String.Copy(str1)
MsgBox(str2)

Output:

Str2="My name is Shyam N. Chawda. "

Equals

 Determines whether two String objects have the same value.

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:

Str = " Hello "

MsgBox(str.Length)

str = str.Trim(str) ‗We can also write like Str=Trim(str)


‗It is not part of String class
MsgBox(str1.Length)

Example:

str = "### Ajit is good boy. ####"

MsgBox(str.Length)

str4 = str.Trim("#")

87
MsgBox(str4)

MsgBox(str4.Length)

Self study TrimStart, TrimEnd ,Ltrim,RTrim

EndsWith

 Checks whether the end of this instance matches the specified String.

 The return type is Boolean.

 It is overload function. We can pass second parameter as case sensitive.

Example:

str = "Zubeidaa"

If str.EndsWith("a") Then

MsgBox("Yes", MsgBoxStyle.Information, "Ans")


Else

MsgBox("No", MsgBoxStyle.Information, "Ans")

End If

Output:
Yes

StartsWith

Exactly opposite of EndsWith. It checks character of starting.

Indexof

 Reports the index of the first occurrence of a String.

Example:

str = "Mughal E Azam is an Excellent movie"

Dim placeNo As Integer

placeNo = str.IndexOf("E")

MsgBox("Place No -> " & placeNo, MsgBoxStyle.Information, "Ans")

placeNo = str.IndexOf("E", 10)

MsgBox("Place No -> " & placeNo, MsgBoxStyle.Information, "Ans")

Output:

88
7,20

Ucase , Lcase , ToUpper , ToLower

Example:
Str = "I AM FROM GONDAL SITUATED IN SAURASHTRA"

Str = str.ToLower()

MsgBox(str, MsgBoxStyle.Information, "To Lower")

str = str.ToUpper()

MsgBox(str, MsgBoxStyle.Information, "To Upper")

str = LCase(str) ‗It is not part of String class

MsgBox(str, MsgBoxStyle.Information, "To Lower")

str = UCase(str) ‗It is not part of String class

MsgBox(str, MsgBoxStyle.Information, "To Lower")

Insert

 Inserts a specified instance of String at a specified index position in this instance.

 Two arguments it (StartIndex,Value). The startIndex means the index position of


the insertion and the Value means The String to insert.

Example:
str = "KABHI ALVIDAA NA KEHNA"

str = str.Insert(5, "abc")

MsgBox(str)

Output:

KABHIabc ALVIDAA NA KEHNA

PadLeft, PadRight

 Both are used for alignment purpose see the below example.

Example:
str = "I have $ 5000"

str = str.PadLeft(25, "0")

MsgBox(str)

Output:
000000000000I have $ 5000

89
Example:
str = "I have $ 5000"

str = str.PadRight(25, "0")

MsgBox(str)
Output:

I have $ 5000000000000000

Remove

 Deletes a specified number of characters from this instance beginning at a


specified position.

 Two arguments of it (StartIndex,Count).

 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"

str = str.Remove(5, 10)

MsgBox(str)
Output:
Vatras good

Replace

 Replaces all occurrences of a specified character or String.

 There are 2 types of arguments of it (Char,Char) and (String,String). It


means overloaded function.

Example:
str = "KABHI ALVIDAA NA KEHNA"

TextBox1.Text = str.Replace("A", "B")

Output:
KBBHI BLVIDBB NB KEHNB

Example:
str = "KABHI ALVIDAA NA KEHNA"

TextBox1.Text = str.Replace("KABHI", "BHABHI")

Output:
BHABHI ALVIDAA NA KEHNA

90
Substring (IMP)

 Retrieves a substring from this instance.

 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

Example: Count the number of even and odd in the string

Dim str As String

Dim i, cntE, cntO As Integer

str = "123456789"

For i = 0 To Len(str) - 1

If str.Substring(i, 1) Mod 2 = 0 Then

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:

Name Description of methods

IsDigit Checks a character is decimal digit or not

IsLetter Checks a character is an alphabetic letter or not

IsLetterOrDigit Checks a character is an alphabetic letter or a decimal digit.

IsLower Checks a character is lowercase letter or not.

IsNumber Checks a character is number or not.

IsPunctuation Checks a character is punctuation mark or not.

IsSeparator Checks a character is separator character or not.

IsSymbol Checks a character is symbol character or not.

IsUpper Checks a character is an uppercase letter or not.

IsWhiteSpace Checks a character is white space or not.

ToLower Converts the value of a character to its lowercase.

ToUpper Converts the value of a character to its uppercase.

Example: Count number of characters in uppercase format in the textbox.

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim str As String,ch As Char,cnt As Integer


str = txtStr.Text

For i = 0 To Len(str) - 1
ch = str.Substring(i, 1)

If Char.IsUpper(ch) = True Then


cnt = cnt + 1
End If
Next
txtAns.Text = cnt

End Sub

92
Other inbuilt functions
Split

 Returns one-dimensional array containing a specified number of substrings.

 By default it splits using Space.

Dim TempA() As String = Split(txtName.Text)

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

Returns a string created by joining a number of substrings contained in an array

Dim temp() As String = {"Maggi", "Kurkure", "Wafer"}

txtAns.Text = Join(temp, ", ")

IIf

 Returns one of two objects, depending on the evaluation of an expression.

 It is like Ternary operator in C or C++.

Syntax:

IIf(Expression,Truepart,Falsepart)

93
Example:

Dim salary As Integer = 50000

Dim strAns As String

strAns = IIf(salary > 30000, "Good", "Bad")

MsgBox(strAns)

Mid

 Returns a string containing a specified number of characters from a string.

 Equivalent to Substring method of String class.

Syntax:

Mid(String,StartIndex,Length)

Example:

Dim MyString, FirstWord, LastWord, MidWords As String

MyString = "Jamnagar is good city" ' Creates text string.

FirstWord = Mid(MyString, 1, 3) ' Returns Jam

LastWord = Mid(MyString, 10, 7) ' Returns is good

MidWords = Mid(MyString, 10) ' Returns is good city

StrReverse

 Returns a string in which the character order of a specified string is reversed.

Syntax:

StrReverse(String)

Example:

Dim myString As String = "YASH IS GOOD BOY"


Dim revString As String

revString = StrReverse(myString) ' Returns "YOB DOOG SI HSAY"

ASC

 Returns ASCII value for the input character.

Syntax:

94
Asc(char) or Asc(string)

Example:

Dim ans As Integer

ans = Asc("a") 'Returns 97


ans = Asc("A") 'Returns 65
ans = Asc("0") 'Returns 48
ans = Asc("9") 'Returns 57

CHR

 Returns return the character associated for the input ASCII number.

 Excatally opposite of ASC function.

Syntax:

Chr(number)

Example:

Dim ans As Char

ans = Chr(97) ‗Returns a


ans = Chr(65) ‗Returns A
ans = Chr(57) ‗Returns 9
ans = Chr(48) ‗Returns 0

Shell

 Runs an executable program.

Syntax:

Shell(path of Exe, Style to open)

Example: Open calculator on button click.

Dim ProcID As Integer

ProcID = Shell("C:\Windows\system32\calc.exe", AppWinStyle.NormalFocus)

95
Example: Open calculator and notepad and send some keys

Private Sub cmdNotepad_Click()

Dim notepadID As Integer

notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)

SendKeys.Send("Hello how are u?")


SendKeys.Send("{Enter}")
SendKeys.Send("I am waiting for u.")

End Sub

Private Sub cmdCalci_Click()

Dim ProcID As Integer

ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)

SendKeys.Send("22")
SendKeys.Send("*")
SendKeys.Send("44")
SendKeys.Send("=")

End Sub

SendKeys

 It provides methods for sending keystrokes to an application.

 .Send is the method of SendKeys class to send particular value to an application.

96
Date-Time Function

Dim dt As Date

REM: Simple store date

dt = #12/21/1982# 'MM/DD/YYYY'

Get the current date or time

txtDate.Text = Today ‗Stores 8/15/2009

txtDate.Text = Now ‗Stores 8/15/2009 9:34:07 PM

txtDate.Text = TimeOfDay ‗Stores 9:35:15 PM

txtDate.Text = DateString ‗08-15-2009

txtDate.Text = TimeString ‗Stores 21:36:17

Return a date

txtDate.Text = DateSerial(2009, 2, 1) ‗Returns 2/1/2009

txtDate.Text = DateValue("10/26/1995") ‗Returns 10/26/1995

Return Time

txtDate.Text = TimeSerial(10, 5, 45) ‗Returns 10/26/1995

txtDate.Text = TimeValue("4:35:17 PM") ‗Returns 10/26/1995

txtDate.Text = TimeValue(#4:35:17 PM#) ‗Returns 4:35:17 PM

Format Function

 Returns a string formatted according to instructions contained in a format String


expression.

 There are 2 arguments of it an expression and style.

Example:

txtDate.Text = Format(Now, "M-d-yy") ‗Stores 5-5-08

txtDate.Text = Format(Now, "MM-dd-yyyy") ‗Stores 05-05-2008

txtDate.Text = Format(Now, "MMMM-d-yyy - dddd")

‗Stores May-05-2008 - Tuesday

txtDate.Text = Format(Now, "hh:mm:ss tt") „Stores 09:58:51 PM

97
Note down the meaning of M,MM,MMMM,d,dd,dd,yy,yyy,yyy,hh,mm,ss,tt

Math Function

Imports System.Math before all the statements.

Dim ans As Double

ans = Sqrt(25) 'Returns 5.0

ans = Round(1339.56) 'Returns 1340.0

ans = Truncate(1339.56) 'Returns 1339.0

ans = Abs(-523) 'Returns 523.0

ans = PI 'Returns 3.1415926535897931

ans = Math.Pow(5, 2) 'Returns 25.0

If we do not want to add Namespace System.Math then write down Math.functionName


as we wrote above in the last line.

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.

Some key facts of the Windows Form.

 A form is a usually rectangular.

 The form is the primary platform for user interaction.

 Forms can be single document interface (SDI) , multiple document interface


(MDI) , dialog boxes etc.

 We can place controls on the form.

 Form is the container.

 Form has properties, events and methods.

 Form can identified by "ME" keyword.

 VB.NET, the support for forms is in the System.Windows.Forms namespace , and


the form class is System.Windows.Forms.Form.

 Form have 2 views: Design View (SHIFT+F7) and Coding View(F7)

Coding Window
Form

99
Some properties of the Form, we can use this property design or runtime both.

Property Name Description


AcceptButton Gets or Sets the one button for the ENTER key.
ActiveForm Gets the currently active form for this application.
AutoScroll It sets scrollbar to the form when its required.
BackColor Background color

BackgroundImage Gets or sets the background image of the form.


CancelButton Gets or sets the one button for the ESC key.
ControlBox By default value of it is True. It‘s related with Maximize,
Minimize and Cancel buttons. If set False all 3 are invisible.
ContextMenu Gets or sets the shortcut menu associated with the control.

Font Gets or sets the font.


ForeColor Gets or sets the font color.
Height Gets or sets the height of the form.

Icon Gets or sets the icon for the form.

IsMdiContainer Gets or sets whether the form is a container for multiple


document interface (MDI).
MaximizeBox and Want Maximize of Mimimize box on the form?
MinimizeBox

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.

Visible Gets or sets a value indicating whether the control is


displayed.

WindowState In which sate we want to open the form. There are 3 options
Normal, Maximize and Minmize. Gets or sets this.

What is the meaning of Gets or Sets for the property?

Exmaple:

Dim no As Integer

no=10 ‗Here we sets the value of variable ―no‖

100
msgbox(no) ‗Here we gets or say fetch the value of variable ―no‖

Same for properties, properties have 3 types.

Readonly
Writeonly
Read and Write

Me.Text=‖Hai‖ ‗Here we sets the value of control.

msgbox(Me.Text) ‗Here we gets or say fetch the value of control.

In the, Text propety we can read and write both.

Example: AcceptButton, CancelButton

Set AcceptButton property -> cmdLogin (Press Enter to execute


event of this button)

Set CancelButton property -> cmdClear (Press Esc to execute


event of this button)

Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdLogin.Click

If LCase(Trim(txtName.Text)) = "manav" And LCase(Trim(txtPassword.Text)) =


"mmm" Then
MsgBox("Welcome",MsgBoxStyle.Information,"Successfully Login")
Else
MsgBox("Access Deined", MsgBoxStyle.Exclamation, "Login Failed")
End If

End Sub

Private Sub cmdClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdClear.Click

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.

 We can navigate between the forms in modeless.

 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.

 Dialog boxes that display important messages must be modal.

 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

Example: Open form as Modal.

Output

103
Private Sub btnName_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnName.Click

Dim frm As New frmName

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.

Example: Open form as Modeless

Output

Private Sub btnOE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnOE.Click

Dim frm As New frmOE

frm.Show()

End Sub

Private Sub btnCal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnCal.Click

Dim frm As New frmSimpleCal

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

2. Using public variable.

Example: Share data of the form using Formname.controlName

Contains 2 textbox controls and 1 button control

txtName , txtSal, btnNext

Form

Contains 2 label controls

lblName, lblSal

Form

Output like this:

Output

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnNext.Click

Dim frm As New frmInfo

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

Below is the coding of second form, in which we will display answer

Public Class frmInfo

Public name As String


Public sal As Double

Private Sub frmInfo_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

lblName.Text = name
lblSal.Text = sal * 12

End Sub

End Class

And below coding written in the First form ,from where we jump

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnNext.Click

Dim frm As New frmInfo

frm.name = txtName.Text
frm.sal = txtSal.Text

frm.Show()

End Sub

106
SDI/MDI
 There are two main styles of user interface:

1. Single-document interface (SDI)


2. Multiple-document interface (MDI).
SDI

 In WordPad, only a single document may be open; we must close one document
in order to open another.

MDI

 The multiple-document interface (MDI) allows you to create an application


that maintains multiple forms within a single container form.

 An MDI application allows us to display or open multiple documents at the same


time.

 Microsoft Excel and Microsoft Word for Windows have multiple-document


interfaces.

 Microsoft Excel allows us to work with several documents at once.

 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

 Create new Project or in Existing Project , Add new form.

 Set properties of the main form like

Name= frmMDI or frmMain


Text=Main
IsMDIContainer = true
WindowState=Maximized.

 Set startup that 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:

And at the bottom of our MDI page

To start building menu, click on the FileToolStripMenuItem object. It will change as


below and the "Type Here" box moves down one place. You get a second "Type Here"
area to the right of the first one.

Click inside the blue "Type Here" area, and the menu changes to this:

The final item we'll add to our menu is an "Exit" item.

We can assign shortcut key

We can get events of menu just double click on it


same like button and start your coding.

Property Window

109
Set the child form‟s properties like

StartPosition = CenterParent
FormBorderStyle=FixedSingle
MaximizeBox = False
ShowInTasbar=False

Form

Coding is given below:

Private Sub PrimeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles PrimeToolStripMenuItem.Click

Dim frm As New frmPrime


frm.MdiParent = Me
frm.Show()

End Sub

Private Sub OddEvenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles OddEvenToolStripMenuItem.Click

Dim frm As New frmOE


frm.MdiParent = Me
frm.Show()

End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ExitToolStripMenuItem.Click

End

End Sub

We can add images to menu control as given below:

Using image property of the MenuStrip control.

Form
Property Window
110
Context Menu

 Context menus are menus that appear when an item is right-clicked.

 Context menu is also known as contextual, shortcut, and popup or pop-up menu.

 Context menu will appear according to area.

 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.

 Given below are the steps to work with ContextMenu control.

 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:

And Type 2 options. Prime No and Odd Even

And at the bottom of our page

Set the ContextMenuStrip property of the


Textbox

Write down the logic as given below on click of

111
the Context men‘s item:

Private Sub OddEvenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles OddEvenToolStripMenuItem.Click

If txtNo.Text Mod 2 = 0 Then


MsgBox("No is even")
Else
MsgBox("No is odd")
End If

End Sub

Private Sub FindPrimeToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles FindPrimeToolStripMenuItem.Click
Logic…
End Sub

Run the project:

Output

112
Exercise 2
Q.1 Answer the following question:

1. Write down the default value of each data type.


2. List out various data types available in VB.NET with its characeteristics.
3. Write down naming rules of variable declaration in VB.NET.
4. Write down the significance of Object data type.
5. What is boxing and unboxing?
6. What is Scope of the variable?
7. Explain Life time of the variable.
8. Explain the concept of Type conversion.
9. What is Ctype function?
10. Explain various types checking function.
11. What is the use Option Explicit?
12. Explain Option Strict concept.
13. How many ways to set Option Explicit option?
14. List out various operators available in VB.NET.
15. Write down the difference between / and \ operator.
16. Explain Like operator with example.
17. Explain GetType operator.
18. Explain AndAlso and OrElse operators.
19. What is the use of ^ operator?
20. How can we write multiple statements in one line? Explain with example.
21. How can we write single statement in multiple line? Explain with example.
22. What is comment? How many ways to do comment? Explain in brief.
23. What is the use of Space () function?
24. How can we give New Line effect?
25. What is the use Me keyword?
26. Explain for..each loop.
27. Explain With..End With block.
28. Explain MsgBox and InputBox functions with example.
29. Explain MessageBox.Show().
30. Explain the concept of modular coding.
31. Explain Sub procedure and Function Procedure with example.
32. What is ByVal and ByRef?
33. Explain the concept of Optional argument.
34. Can we return more than one value from the function?
35. Explain various exit statement.
36. Explain various string functions.
37. Explain Format function with example.
38. Give demo of Split and Join functions.
39. Explain Asc and Chr functions.
40. What is Form?
41. Explain Modal and Modeless form with example.
42. Explain MDI and SDI form with example.
43. Is it possible to access variables and controls of one form to another form?
44. What is the constant variable? How can we define it in Vb.net
45. What is design time and runtime?
46. What is sender and e?
47. Explain menu and context menu.
48. How can we refer the current form?

Q.2 Compare

1. MDI and SDI


2. Modal and Modeless form
3. Sub procedure and Function Procedure
4. MsgBox and MessageBox.Show
5. If..Then..Else and Select..Case block.
6. AndAlso operator and And operator.
7. OrElse operator and Or operator.
8. ByVal and ByRef

Q.3 Write down True or False

1. Dim no1 As Integer = 5, no2 As Double = 7 is valid statement.


2. Dim _1 As Integer
3. Dim _ As String
4. Dim 1AB As String
5. Dim MN$12 As String
6. VB.NET is case sensitive programming language.
7. Char to String is an example of Narrowing to Widening conversion.
8. Decimal to Integer is an example of Narrowing to Widening conversion.
9. IsDBNull and IsNothing both are perform same task.
10. By default Option Strict is Off.
11. By default Option Explicit is Off.
12. We can declare Option Strict anywhere in our program.
13. It‘s compulsory to write Option Explicit in each form.
14. / Operator is known as Integer division.
15. "aM5a2" Like "a[B-T]*" will return False.
16. "MAT456pqr" Like "B?T*" will return True.
17. Mod operator returns square of number.
18. (―) is used for comment the statement.
19. We can write multiple If.. block.
20. We can not take String data as a Case in Select Case block.
21. We should write Else block with each If block.
22. With..End with is a type of loop.
23. ByRef is by default in procedures of VB.NET.
24. The full form of MDI is many document interface.
25. The messagebox is modelss dialog box.

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.

31. Count Odds and Evens in any string.


32. Given as below:

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.

 Errors are drawbacks of the program.

 Error is also known as an exception.

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.

 Also known as a Design time error.

 Visual Basic checks our code as we type and alerts if we made a mistake.

 It is the most common type of errors.

 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"

Caption is not a property of the command button.

 txtNo.tet=‖abc‖

 Dim No Integer

Run-Time Errors

 As their name suggests, these errors occur when the program is running.

 Runtime errors usually cause your program to crash.

 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.

 We can fix most run-time errors by rewriting the wrong code.

117
Example

 Trying to open a file that doesn‘t exist.

 Trying to access CD that is corrupted.

 Trying to check email with an incorrect username or password

 Dividing a number by 0.

 Users entering character data where a number is expected.

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.

 Programmer‘s logical mistake.

 Logic errors are generally the difficult to identify.

 Example: Instead of doing Multiplication we write the logic of division then.

Example

 Ans=5 * 10 ‗instead of + programmer write X

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.

 If a programmer do not provide a mechanism to handle these errors the


program‘s execution is terminates.

There are 2 ways to trap errors in VB.NET and gives proper message while error will
trap.

1. Structured Exception Handling


2. Unstructured Exception Handling (Old VB6.0)

Structured Exception Handling

 We can use the Try...Catch...Finally statements for structured exception handling.

 It provides a way to handle errors.

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

Finally section: Always gets executed

 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.

 If an exception occurs, Visual Basic examines the Catch statements. If it finds a


Catch statement that handles the generated exception, it executes the
corresponding statement block. When it has finished executing the Catch block, it
executes the Finally block if it is present.

119
 We can have any number of Catch statements or none.

 We can include or omit a Finally statement.

 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.

 Both Catch and Finally blocks are optional.

 The Try block can exist either with one or more Catch blocks or a Finally block or
with both catch and finally blocks.

 All exceptions are directly or indirectly inherited from the Exception


class.

 We can catch all exceptions using Catch ex As Exception block.

 In Try...Catch...Finally block Catch ex As Exception statment is like Case Else


option of Select Case. If we include multiple catch block in our program then
write Catch ex As Exception last in all the Catch statement.

 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.

Example: Addition of 2 numbers

Private Sub btnAns_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnAns.Click

Try

Dim no1, no2 As Integer, ans As Integer


no1 = txtNo1.Text
no2 = txtNo2.Text

ans = no1 + no2

MsgBox(ans, MsgBoxStyle.Information, "Demo") Output

Catch ex As Exception

MsgBox(ex.ToString, MsgBoxStyle.Critical, "Error")

Finally

120
MsgBox("Hai in Finally", MsgBoxStyle.Information, "Demo")

End Try

End Sub

Example: Enter wrong data in above program

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.

Example: Demo of ex.Message

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Try

Dim no1, no2 As Integer, ans As Integer


no1 = txtNo1.Text
no2 = txtNo2.Text

ans = no1 + no2

MsgBox(ans, MsgBoxStyle.Information, "Demo")

Catch ex As Exception

MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

Finally

MsgBox("Hai in Finally", MsgBoxStyle.Information, "Demo")

121
End Try

End Sub

Sometimes it‟s good to be precise about what kind of exception we are trying to
check for.

Example: Divison of 2 numbers and multi catch

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

Most common Exceptions are

OutOfMemoryException
NullReferenceException
InvalidCastException
ArrayTypeMismatchException
IndexOutOfRangeException
ArithmeticException
DevideByZeroException
OverFlowException
FileNotFoundException
DirectoryNotFoundException

122
Unstrucuterd exception handling
It‘s simple to use.

In .NET environment, programmers are using Strucuted expception handling.

Unstructured are used in VB6.0. So don‘t use this concept in VB.NET.

On Error Go To statement enables exception handling and specifies the location of the
exception-handling code.

There are three ways to handle errors:

 On Error GoTo <label>


 On Error Resume Next
 On Error GoTo 0

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.

Example: Using on Error Goto <label>

Dim n, m, ans As Integer

On Error GoTo Help

n = txtNo1.Text
m = txtNo2.Text
ans = n / m
MsgBox("Ans = " & ans)

Help:
MsgBox("Some error", MsgBoxStyle.Critical, "error")

Example: Using on Error Resume Next

Dim n, m, ans As Integer

On Error Resume Next


n = txtNo1.Text
m = txtNo2.Text
ans = n / m
MsgBox("Ans = " & ans)

123
What is debugging?
 It's an art of identifying our bugs in program.

 Debugging is an important skill of any programmer.

 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:

And line is highlighted brown.

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.

Bottom of the form Watch Window will appear

Runtime
Watch Window

125
What is COM?
 Component Object Model (COM) is a standard introduced by Microsoft.

 COM is developed by Microsoft to build component-based applications.

 COM is a software component model that is a specification for how to develop


reusable software components and how these component objects can
communicate with each other.

 COM is a platform-independent, distributed, object-oriented system for creating


binary software components that can interact.

 It can be used in different environments even other than where it was created

 It can be used across the machine boundaries

 It has been implemented on several platforms COM is primarily used with


Microsoft Windows.

 COM objects are discrete components, each with a unique identity, which expose
interfaces that allow applications and other components to access their features.

 They are completely language-independent.

 They have built-in interprocess communications capability, and easily fit into an
object-oriented program design.

 COM is based on Client/Server model.

 Each COM object operates as a server that receives and processes requests from
a client program, and generates responses

 A COM client is sometimes called a container. A COM object is sometimes called a


control.

 COM components have globally unique identifier, or GUID. It is the unique


software-readable name.

Characteristics of a COM object

 It may contain data


 It has one or more set of functions called interface.
 It‘s identified by a GUID.
 It provides methods to their clients can call.

The main benefits of COM are as follows.

 COM is object oriented.


 COM provides a consistent binary interface.
 COM is language independent.
 Code reusability.
 A binary standard to call functions between components.

We can add COM components by Project -> Add Reference ->

126
What is DCOM?
 The full form of DCOM is Distributed Component Object Model.

 It is an extension of the Component Object Model (COM) that allows COM


components to communicate across network boundaries.

 It provides rich, symmetric communication between components.

 It can be robustly expanded to meet new functional requirements.

 It can be efficiently deployed and administered.

 It‘s a big brother of COM but the difference is that it process are spread across a
network.

 It‘s an open technology.

 DCOM communications also work between dissimilar computer hardware and OS.

 COM components can only perform interprocess communication on the same


machine.

 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

Component object model Distributed Component object model


Execution is done in its client Run on selected server
Machine
COM processes can run on the same Network-based component interaction.
machine
Inprocess Outprocess
DCOM is improved version of the COM

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).

 The managed code is always executed by a managed runtime execution


environment rather than the operating system directly.

 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 is always compiled into an Intermediate Language.

 Managed code also provides platform independence.

 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.

 CLR provides core services such as memory management, thread management,


etc.

 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.

 Code that is directly executed by the Operating System is known as un-managed


code.

 Unmanaged code is one that is run by windows operating system.

 Typically applications written in VB 6.0, C++, C, COM components, ActiveX


components, and Win32 API functions are examples of unmanaged code.

 Unmanaged code typically targets the processor architecture and is always


dependent on the computer architecture.

 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.

 Unmanaged code is always compiled to the native code which is architecture


specific.

 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.

Summary of Managed and Unmanaged code

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.1 Write down the answers of following questions:

1. Explain COM and DCOM.


2. Explain Manged and Unmanged code.
3. Explain error with its type.
4. What is exception handling?
5. Explain Strucuted excpetion handling.
6. Explain Unstructured exception handling.
7. What is debugging? Explain debugging techniques.
8. Explain Add Watch and Quick Watch.
9. Write down difference between Add Watch and Quick Watch.
10. How can we add COM componenet in out program?

Q.2 Compare

1. F10 and F11 keys for debugging.


2. Manged and Unmanged code.
3. COM and DCOM.

130
Chapter - 3

What is Control?
A control is an object that can be drawn on to the Form.

Mainly controls are visible object.

The controls are to enable or enhance user interaction with the application.

Examples of these controls are TextBox, Button, Checkbox, Label ,Timer,


TreeView, etc.

All controls are unique with through its features.

All the controls have properties, methods, and events.

Control class is the base class of all the windows controls.

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:

1. Dragging and dropping


2. Double click on the control

We can set their properties in the properties window

We can add controls at runtime as given steps below:

1. Create an object of Control.


2. Set the properties of it.
3. Add that controls to the form using Me.Controls.Add(Ctlobj)

Design Time Form Run Time Form

Private Sub frmCtl_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

Dim txt As New TextBox


Dim btn As New Button

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

Some common properties of the controls are as given below:

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

Some common events of the controls are as given below:

Event Description
Click Occurs when the control is clicked.

GotFocus Occurs when the control receives focus.

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.

LostFocus Occurs when the control loses focus.

MouseClick Occurs when the control is clicked by the mouse.

MouseDown Occurs when the mouse pointer is over the control and a mouse
button is pressed.

MouseEnter Occurs when the mouse pointer enters the control.

MouseHover Occurs when the mouse pointer rests on the control.

MouseLeave Occurs when the mouse pointer leaves the control.

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.

We can set TAB order by:

1. Manually using TabStop and TabIndex property for each control

2. View -> TabOrder

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.

 They are sometimes called an edit field or edit control.

 Typically, a TextBox control is used to display, or accept as input, a single line of


text.

 TextBox can display multiple lines.

 TextBox control can work as a Password input control.

 By default, a TextBox holds up to 32767 characters, but when displaying multiple


lines, a text box holds up to 2GB of text.

 TextBox can be read-only.

 The prefix of the TextBox is ―txt‖.


SingleLine TextBox

Password Cacher TextBox

Multiline TextBox

Some Properties of the TextBox:

AcceptsTab

 Either True or False.

 Indicates if tab characters are accepted as input for multiline TextBox.

 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.

BackColor - The background color of the TextBox

BorderStyle – The border style can be Fixed3D (3D border), Fixed Single (single-line
border) or None (No border).

CharacterCasing – We can set the case of the TextBox to


Lower, Upper or Normal Case.

Cursor - The cursor that appears when the mouse passes over the
control.

Enable

 Either True or False.

 If True we can enter the data at runtime ; if False then we


can not edit the value of it like label.

 The default value is True.

Font - The font style of the TextBox.

ForeColor - The foreground color (font color) of the TextBox.

MaxLength

 It specifies the maximum number of characters that can be entered into the
TextBox.

 0 means no limit.

 The default value is 32767 characters.

MultiLine

 Either True or False.

 If set True then we can increase the height of the TextBox control.

 We can not use PasswordChar and Multiline properties together.

 The default value is True.

PasswordChar

135
 Indicates the character as a Password.

 We can enter *,?,etc. characters for Password.

ReadOnly

 Either True or False.

 The text of the TextBox control can be not be change at runtime.

 The default value is False.

ScrollBars - Either True or False , for multiline TextBox.

TabIndex - The index in the tab order sequence

TabStop - Indicates whether the user can use the Tab key to give focus to the control

Text - The text contained in the control

TextAlign – Alignment of the TextBox Left , Right or Center.

Visible - Either True or False , To hide the TextBox

WordWrap - Either True or False. It wraps the words in the TextBox.

Some Methods of the TextBox:

Clear - Clears all text from the TextBox

ClearUndo - Redo

Copy - Copies the current selection in the TextBox to the Clipboard.

Cut - Cut the current selection in the TextBox to the Clipboard.

Focus - Sets focus to the TextBox.

Paste

Undo - Undoes the last formatted operation in the TextBox.

Example: Small Notepad

Private Sub btnCut_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnCut.Click

txtData.Cut()

End Sub

Private Sub btnCopy_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnCopy.Click

136
txtData.Copy()

End Sub Form

Private Sub btnPaste_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnPaste.Click

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

If txtData.CanUndo = True Then


txtData.Undo()
txtData.ClearUndo()
End If

End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click

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

Private Sub btnLcase_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnLcase.Click

txtData.Text = LCase(txtData.Text)

End Sub

Some Events of the TextBox:

TextChanged - Fires when the Text property value changes.

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

Step1: Add Error provider control to our form

Step2: Write down coding in KeyPress event.

If we press digits then


ErrorProvider will
display

Private Sub txtName_KeyPress(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyPressEventArgs) Handles txtName.KeyPress

If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Then


e.Handled = True
ErrorProvider1.SetError(txtName, "Plz enter only String")
Else
e.Handled = False
End If

End Sub

Private Sub txtAge_KeyPress(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyPressEventArgs) Handles txtAge.KeyPress

If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 8 Then


e.Handled = False
Else
e.Handled = True
ErrorProvider1.SetError(txtAge, "Plz enter only Numeric")
End If

End Sub

138
ErrorProvider Control

It provides an easy way to set validation errors.

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.

Some properties of this controls are : Icon, BlinkRate, BlinkStyle.

The method which we use is SetError(CtrlName,Msg)

Button control

 It is one of the most popular control in Windows Base


Application.

 It is also known as a Command Button.

 The prefix of the Button is either ―btn‖ or ―cmd‖.

 Some Properties of the Button are Name, Text, BackColor, ForeColor, etc.

 We can set Accelator key for the Button and Menu.

 Accelator key are also known as a mnemonics.

 Accelator keys are represented by the underlined characters.

 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

 It is used to display text.

 Runtime we can not edit the text of label.

 The prefix of the Label is ―lbl‖.

139
 Mostly the Label control is used for displaying the answers and meaningful
notation.

 The common property of the Label is Text.

140
RadioButton control

 It is also known as an option button.

 A RadioButton control is rounded in shape.

 The prefix of the RaduiButton is either ―opt‖ or ―rad‖.

 We can Checked or Unchecked the radiobutton.

 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.

 RadioButton can make its own group when kept in container.

 To create multiple groups on one form, place each group in its own container,
such as a GroupBox or Panel control.

 Most usefull property of the RadioButton is Checked - Default value is False,


set it to True if you want the RadioButton to be displayed as checked.

 The CheckedChanged event is raised when the value of the Checked


property changes it state.

Example:

Here the name of TextBox is txtName, Radiobutton names are optMale, optFemale and
Button name is btnAns.

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim str As String

str = "Your name is " & txtName.Text

If optMale.Checked = True Then

str &= " Your gender is Male"

Else

str &= " Your gender is Female"

End If

MsgBox(str, MsgBoxStyle.Information, "Hello")


Output

End Sub

141
Example: According to RadioButton selection display the appropriate image on
lable control.

Here the names of Radiobutton are optMale, optFemale and


PictureBox name is PictureBox1.

Private Sub optMale_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
optMale.CheckedChanged

PictureBox1.Image = Image.FromFile("e:\Boy.gif")

End Sub
Output

Private Sub optFemale_CheckedChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles optFemale.CheckedChanged

PictureBox1.Image = Image.FromFile("e:\Girl.gif")

End Sub

PictureBox control

PictureBox control is used to display images on it.

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.

Here the names of Radiobutton are optBBA and optBCA


which are in GroupBox1 container.The other GroupBox2
contains optNormal, optSC, optST. The name of the Label
control is lblAns.The name of the Button is btnAns.

Private Sub btnAns_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnAns.Click

If optBCA.Checked = True Then

If optSCST.Checked = True Then

lblAns.Text = 50
Output
ElseIf optNormal.Checked = True Then

lblAns.Text = 30

ElseIf optSEBC.Checked = True Then

142
lblAns.Text = 15

End If

ElseIf optBBA.Checked = True Then

If optSCST.Checked = True Then

lblAns.Text = 70

ElseIf optNormal.Checked = True Then

lblAns.Text = 10

ElseIf optSEBC.Checked = True Then

lblAns.Text = 5

End If

End If

End Sub

143
GroupBox and Panel

 Panel and GroupBox controls are that contains other controls.

 They both work as a Container of other controls.

 Use GroupBox and Panel to logically group a collection of controls on a form.

 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.

 By default Panel control is displayed without any borders.

 Panel control does not have Text property.

 The GroupBox display a border around a group of controls with or without a


caption.

 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

No Have BorderStyle property


No scrollbar Have the capability to scroll by setting
its AutoScroll property to True
Has ability to set a title Does not have ability to set a title or
caption.
No Have TabStop property

144
CheckBox control

 A checkbox is clicked to select and clicked again to deselect some option.

 When a checkbox is checked a check (a tick mark) appears indicating a selection.

 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.

 The prefix of the CheckBox control is ―chk‖.

Some Properties of the CheckBox:

Text – Caption of the CheckBox.

Checked – True or False, which indicates the state of the CheckBox whether the
CheckBox is Checked or UnChecked.

CheckedState – There are 3 options as given below:

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.

Example: Display whether the checkbox is selected or not.

145
Private Sub chkSports_CheckedChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles chkSports.CheckedChanged

If chkSports.Checked = True Then

MsgBox("Sports Checked", , "chekcbox")

ElseIf chkSports.Checked = False Then

MsgBox("Sports UnChecked", , "chekcbox")

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.

 The prefix of the ListBox is ―lst‖.

 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.

 A scroll bar automatically appears when many items in the ListBox.

 By default we can select only single item from the ListBox.

Some Properties of the ListBox:

Items – List of the data in the ListBox.

Example: Coding for Add items in the ListBox.

Private Sub frmLstBox_Load(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load

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.

SelectionMode – The values of selectionMode are as given below:

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)

Example: Change Selection mode

lstBox lstMode

Private Sub lstMode_SelectedIndexChanged(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles lstMode.SelectedIndexChanged

If lstMode.SelectedItem = "MultiExtended" Then


lstBox.SelectionMode = SelectionMode.MultiExtended

ElseIf lstMode.SelectedItem = "MultiSimple" Then


lstBox.SelectionMode = SelectionMode.MultiSimple

ElseIf lstMode.SelectedItem = "None" Then


lstBox.SelectionMode = SelectionMode.None

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.

 It returns the text of selected item.

 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.

 Use this for more than one selected items.

SelectedIndex

 It is read-only property.

 It returns the index of the selected item.

 If more than one item is selected, this property represents the lowest index.

 If no item is selected, the property returns -1.

SelectedIndices

 This read-only property returns all the indices of selected items in the ListBox.

 Use this for more than one selected items.

Example: Demo of all 4 properties given above.

Private Sub frmLstBox_Load(ByVal sender As


System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load

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

MsgBox(lstCity.SelectedIndex, MsgBoxStyle.Information, "Listbox")

End Sub

Private Sub btnSelectedValue_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSelectedValue.Click

MsgBox(lstCity.SelectedItem, MsgBoxStyle.Information, "Listbox")

End Sub

Private Sub btnSelectedIndices_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSelectedIndices.Click

Dim i As Integer

For i = 0 To lstCity.SelectedIndices.Count - 1

MsgBox(lstCity.SelectedIndices.Item(i))

Next

End Sub

Private Sub btnSelectedValues_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSelectedValues.Click

Dim i As Integer

For i = 0 To lstCity.SelectedItems.Count - 1

MsgBox(lstCity.SelectedItems.Item(i))

Next

End Sub

Text - It returns the currently selected item's text.

Some Methods of ListBox:

ClearSelected() - UnSelects all items in a ListBox.

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"))

GetSelected() – It checkes whether given index of the item is Selected or not. It


returns Boolean answer for the given index.If selected then returns True.

150
Example: MsgBox(lstCity.GetSelected(0))

SetSelected() – It selects or deselects the item of the given index.

Example:

lstCity.SetSelected(3, True)
lstCity.SetSelected(4, False)

Example: Select all the items having even index.

Private Sub btnAll_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnAll.Click

Dim i As Integer

For i = 0 To lstCity.Items.Count - 1 Step 2

lstCity.SetSelected(i, True)

Next

End Sub Output

Example: Display state of each item in the


ListBox.

Private Sub btnAns_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs)
Handles btnAns.Click

Dim i As Integer
Dim str As String = ""

For i = 0 To lstData.Items.Count - 1 Output


str &= "The item " & i & " is " & lstData.GetSelected(i)

str &= vbNewLine

Next

MsgBox(str)

End Sub

The most usefull event of the ListBox is SelectedIndexChanged. It occurs when


the SelectedIndex property has changed.

151
Items collection

The items in the ListBox are stored in the Items


collection.

Properties of Items collection are Count, Items, etc.

Count – It returns total number of elements in the


ListBox.

Example: MsgBox(lstName.Items.Count) Coding Window

Items – It returns the text of the given index.

Example: MsgBox(lstName.Items.Item(0))

Methods of the Items collection:

Add() – It adds items in the ListBox.

Example:

lstName.Items.Add("Mansi")

Example:

With lstName.Items
.Add("Kruti")
.Add("Manav")
.Add("Niyati")
End With

Example:

Dim Item_name As String

Item_name = InputBox("Enter Item", "")

lstName.Items.Add(Item_name)

AddRange() – It adds a group of items to the list of ListBox.

Dim str_Array(4) As String

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)

Clear() – It clears all the items from the ListBox.

Example: lstName.Items.Clear()

152
Contains()

It returns Boolean answer.

It checks whether the given object is in the list of ListBox or not.

Example:

If lstName.Items.Contains("Ram") = True Then


MsgBox("Yes")
Else
MsgBox("No")
End If

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()

It contains 2 arguments. Index and Value.

We can insert item in the ListBox in any place by using Insert method.

Example: lstName.Items.Insert(0, "Devdas") It adds the Devdas at 0th position.

Remove() – It removes the item from the ListBox. The argument of Remove() method
is the object.

Example: lstName.Items.Remove("Ripal")

RemoveAt() – It removes the item from the ListBox by index.

Example: lstName.Items.RemoveAt(0)

Example: Demo of Insert, Add, Remove methods.

Controls name like


lstName,txtName,txtPos,txtVal,btnAdd,btnRemove,btnInsert

Private Sub btnAdd_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnAdd.Click

lstName.Items.Add(txtName.Text)
txtName.Clear()

End Sub

Private Sub btnRemove_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnRemove.Click

If lstName.Items.Contains(txtName.Text) Then
Output
153
lstName.Items.Remove(txtName.Text)

End If

txtName.Clear()

End Sub

Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnInsert.Click

lstName.Items.Insert(txtPos.Text, txtVal.Text)
txtPos.Clear()
txtVal.Clear()

End Sub

Example: Most IMP

Private Sub btnShift1right_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnShift1right.Click

lstYourMenu.Items.Add(lstMenu.SelectedItem)
lstMenu.Items.Remove(lstMenu.SelectedItem)

End Sub

Private Sub btnShift1left_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnShift1left.Click
Output
lstMenu.Items.Add(lstYourMenu.SelectedItem)
lstYourMenu.Items.Remove(lstYourMenu.SelectedItem)

End Sub

Private Sub btnAllright_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAllright.Click

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

Private Sub btnAllLeft_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAllLeft.Click

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

Private Sub btnShiftMright_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnShiftMright.Click

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

Private Sub btnShiftMleft_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnShiftMleft.Click
Dim i As Integer

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

 It is a combination of a ListBox and a CheckBox.

 Displays a ListBox in which a check box is displayed to the left of each item.

 By default we can checked items in CheckedListBox by double click on item.We


can set Single click selection by CheckOnClick property.

 The prefix of the CheckedListBox is ―chkLst‖.

 CheckedListBox is derived from the ListBox it shares all the members of ListBox.

 The CheckedListBox have same properties as ListBox like Items,MultiColumn,


ScrollAlwaysVisible ,Sorted, SelectedIndex, SelectedItem, etc.

 The CheckedListBox have same methods as ListBox.

 The CheckedListBox have same Items collection as ListBox. We can write


chLst1.Items.Add(),chLst1.Items.Remove(), etc.

 The main event of the CheckedListBox is SelectedIndexChanged as ListBox.

The new properties of the CheckedListBox are as given below:

CheckOnClick – True or False. if set True then check box is checked with the first click
of an item.

ThreeDCheckBoxes – Display of CheckBox either flat or 3D check marks.

The new methods of the CheckedListBox are as given below:

GetItemChecked() – It checkes whether given index of the item is Checked or not. It


returns Boolean answer for the given index.If selected then returns True.

Example: MsgBox(chklstHobby.GetItemChecked(0))

SetItemChecked() – It checked or unchecked the item of the given index.

Example: chkLstHobby.SetItemChecked(0,True)

Example: Take input from the user in the TextBox


for starting character and Check all the ListItem
whose starting character is that.

Private Sub btnChecked_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnChecked.Click

Dim str As String


Dim i As Integer

For i = 0 To chkLstMovie.Items.Count - 1

156
str = chkLstMovie.Items.Item(i)

If str.StartsWith(txtStr.Text) = True Then

chkLstMovie.SetItemChecked(i, True)

Else

chkLstMovie.SetItemChecked(i, False)
End If
Next
End Sub

Private Sub btnUnChecked_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnUnChecked.Click
Dim i As Integer

For i = 0 To chkLstMovie.Items.Count - 1

chkLstMovie.SetItemChecked(i, False)

Next

End Sub

Example: Display only Checked Items from the CheckedListBox.

Private Sub btnAns_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs)
Handles btnAns.Click

Dim i As Integer
Dim str As String = ""

For i = 0 To chkLstMovie.Items.Count - 1

If chkLstMovie.GetItemChecked(i) = True Then

str &= chkLstMovie.Items.Item(i) & vbNewLine

End If

Next
Output
MsgBox(str, MsgBoxStyle.Information, "Ans")

End Sub

GetItemCheckState() - Returns a value indicating the check state of the current item.

SetItemCheckState() - Sets Checked, Indeterminate or Unchecked state to the


indicated 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

Private Sub btnUnChkState_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnUnChkState.Click

Dim i As Integer

For i = 0 To chkLstMovie.Items.Count - 1
Output
chkLstMovie.SetItemCheckState(i, CheckState.Unchecked)

Next

End Sub

158
ComboBox Control

 ComboBox is a combination of a TextBox and a ListBox.

 The ComboBox displays an editing field (TextBox) combined with a ListBox


allowing us to select from the list or to enter new text.

 RunTime user can enter new data to the ComboBox control but new data store in
it temporary.

 ComboBox displays data in a drop-down style format.

 The prefix of ComboBox is ―cmb‖.

 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

 The combo box has TextBox + ListBox.

 The text portion is editable. The list portion is always visible.

 The list doesn‘t have drop down effect.

DropDown (By default)

159
 The text portion is editable.

 The user must click the arrow button to display the list portion.

DropDownList DropDown

DropDownList

 User can not type in the ComboBox.

 ComboBox is like ListBox.

 The user can only choose an item in the list.

The ComboBox has same Items collection as ListBox and CheckedListBox control.

So, we can use Items.Add(),Items.Clear(),.Items.Remove(), etc methods and properties


of Items collection.

Some Properties of the ComboBox:

MaxDropDownItems - Gets or sets the maximum number of items to be displayed in


the drop-down of the ComboBox.

Set MaxDropDownItems=2

Property Window
Output

SelectedIndex - Gets or sets the selected item's index.

SelectedItem - Gets or sets selected item.

160
Sorted - True or False. Gets or sets whether the items in the combo box are sorted.

Text - Gets or sets selected item's text.

Example: Demo of count property and some


methods.

Private Sub btnAdd_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnAdd.Click

Dim str As String

str = InputBox("Enter item")

If cmbCity.FindString(str) > -1 Then

MsgBox("Already in the list",


MsgBoxStyle.Critical, "error")
Else
cmbCity.Items.Add(str)
End If
End Sub Output

Private Sub btnRemoveSelected_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnRemoveSelected.Click

cmbCity.Items.Remove(cmbCity.SelectedItem)

End Sub

Private Sub btnRemoveAt_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnRemoveAt.Click

cmbCity.Items.RemoveAt(cmbCity.SelectedIndex)

End Sub

Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnInsert.Click

Dim pos, str As String

pos = InputBox("Enter position")


str = InputBox("Enter item")

If cmbCity.FindString(str) > -1 Then


MsgBox("Already in the list", MsgBoxStyle.Critical, "error")
Else
cmbCity.Items.Insert(pos, str)
End If

End Sub

Private Sub btnSIndex_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSIndex.Click

161
MsgBox(cmbCity.SelectedIndex)

End Sub

Private Sub btnSItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSItem.Click

MsgBox(cmbCity.SelectedItem)

End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click

cmbCity.Items.Clear()

End Sub

Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCount.Click

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

Private Sub frmComBo_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

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

Private Sub cmbRollNo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles cmbRollNo.SelectedIndexChanged

cmbName.SelectedIndex = cmbRollNo.SelectedIndex

End Sub

Private Sub cmbName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles cmbName.SelectedIndexChanged

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.

 It is very common control for any Windwos base application.

 In Microsoft Word or Excel we can see left and bottom side Scrollbar.

 There are 2 types of ScrollBar : HScrollBar and VScrollBar.

 The difference between HScrollBar and VScrollBar is presentation horizontally and


vertically nothing else.

 User select a value between the 2 ends of the 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.

 The scrollbar can scroll = Maximum - LargeChange + 1

SmallChange

LargeChange

Indicator represents current Value

Some Properties of the ScrollBar:

Minimum

 Gets or sets the lower limit of the ScrollBar.

 The default value is 0.

Maximum

 Gets or sets the upper limit of the ScrollBar.

 The default value is 100.

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.

 Gets or sets that value.

 The default value is 1.

LargeChange

 When we click in between indicator and left or right side arrow it is called
LargeChange.

 Gets or sets that value.

 The default value is 10.

Value

 The control‘s current value, specified by the indicator‘s position

 Gets or sets a numeric value for the current position.

 It follows between the Minimum and Maximum range.

 The default value is 0.

The scrollbar can scroll = Maximum - LargeChange + 1

So if we set Maximum property=200 and Largechange=10

Then scrollbar can scroll

200-10+1 = 191

if we want to scroll upto 200 then set Maximum=209.

209-10+1= 200

165
The scrollbar‟s events fire when

1. By clicking the 2 arrows at its ends

2. By clicking the area between the indicator and arrows

3. By dragging the indicator with the mouse

The important event of the ScrollBar as given below:

Scroll Event

 Default event of the ScrollBar.

 Fires when the ScrollBar has been moved by


either a mouse or keyboard action.

 We can get more information from the ―e‖


argument like NewValue,OldValue,Type of
scrolling, ScrollOrientation,etc.

 e.Type specifies the type of action used to raise


the Scroll event like LargeDecrement ,
SmallIncrement etc.
Design View
ValueChanged Event

 Fires when the Value property has changed, either by a Scroll event or
programmatically.

 It fires parallel to the Scroll event.

 But extrea it fires when the programmer write


as given below:

HScrollBar1.Value = 20 Design View

 Means the value is changed but due to


programmer coding not due scrolling. So, this time only ValueChanged event fire.

 We can not get any information from “e” argument of ValueChanged event as
above image.

So we can write coding Scroll and ValueChanged any of it.

Example: Find Maximum between 2 ScrollBar.

Output

166
Private Sub btnMax_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMax.Click

If HScrollBar1.Value > HScrollBar2.Value Then

Me.Text = "HscrollBar1 is max"

Else

Me.Text = "HscrollBar2 is max"

End If

End Sub

Example: Display the picture on the position of Scrollbar.

Dim pict_Path(4) As String

Private Sub frmScrollPict_Load(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load

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

Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll

PictureBox1.Image = Image.FromFile(pict_Path(HScrollBar1.Value - 1))

Me.Text = HScrollBar1.Value

End Sub

167
TrackBar Control

It is a similar to the ScrollBar that allows the user to scroll


through a range of values.

The TrackBar control commonly used in Volume organizer,


Display properties Settings,etc..

The user can change the value of the TrackBar by dragging the slider, using the arrow
keys, Page Up or Page Down keys.

ToolBox contains only one Trackbar control .

It displayed horizontally or vertically,using Orientation property.

The formula of ScrollBar can scroll is not applied over here.

TrackBar control has same properties ,events and methods like ScrollBar.

Some Properties of the TrackBar:

Oritentation - Horizontal or Vertical TrackBar.

TickStyle

It indicates where the ticks appear on the track bar.

There are 4 options

1. None

2. TopLeft

3. BottomRight

4. Both

168
TickFrquency

The number of position between tick marks.

For example, set Maximum=50, Minimum=1 and TickFrequency =5 then

Position between Tick Marks=


Maximum/TickFrquency

PBTM= 50/5

PBTM =10

For example, set Maximum=50, Minimum=1 and TickFrequency =10 then

PBTM = 50/10

PBTM =5

Example: Print the Table accroding to position of the TrackBar.

Output

Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles TrackBar1.Scroll

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

Private Sub TrackBarRed_Scroll(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles TrackBarRed.Scroll, TrackBarGreen.Scroll,
TrackBarBlue.Scroll

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.

The Common dialog controls are given below:

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.

When a Common dialog control is


added to a project, a new icon
appears in the components tray of
the form.

They do not place any specific


postion of the Form like other
controls are placed.

Design View

To display Common dialog control at runtime we need to call .ShowDialog() method of


the dialog control.

Here we are going to view Common dialog controls with RichTextBox control.
RichTextBox control is an advance version of the TextBox control.

.ShowDialog() method returns the value as given in below image:

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

Color Dialog allow us to select a color.

The image right side displays a color dialog.

User can select easily color from it.

We can get/set selected color value in Color property.

Property Window

Properties of the ColorDialog controls are as given below:

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

 Gets or sets the selected color value.

 Default color is black.

 If we set this property before opening the Color dialog box,the selected color will
display on the Color dialog box.

Example: Set color property runtime or design time.

Runtime(Coding)

Private Sub btnColorDg_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnColorDg.Click

With ColorDialog1

172
.Color = Color.Orange

If .ShowDialog() = Windows.Forms.DialogResult.OK Then


Me.BackColor = .Color

End If
End With

End Sub

Output:

FullOpen

 True or False

 Default value is False.

 If we want to give default color dialog with custom color then set value True for
the FullOpen property.

 If AllowFullOpen is false, then FullOpen has no effect.

Example: Set FullOpen property as True and see effect.

Property Window

Private Sub btnColorDg_Click()

If ColorDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then Output


Me.BackColor = ColorDialog1.Color
End If

173
End Sub

Example: Color Dialog usage

Private Sub btnBackColor_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnBackColor.Click

If ColorDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

RichTextBox1.BackColor = ColorDialog1.Color

End If

End Sub

Private Sub btnFontColor_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnFontColor.Click

If ColorDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

RichTextBox1.ForeColor = ColorDialog1.Color

End If

End Sub

174
FontDialog

Font Dialog allow us to select a font size, face, style, etc.

AllowSimulations

ShowApply

MaxSize,MinSize

ShowEffect

ShowColor
AllowScriptChange

Some Properties of FontDialog

Keep in mind above image for understand below properties


because all the properties are related with area.

AllowSimulations

 True or False.

 Default value is True.

 See above image for AllowSimulations area.

AllowScriptChange

 True or False.

 Default value is True.

Property Window
175
 Whether the user can change the character set specified in the Script.

Color

 True or False.

 Default value is False.

 It returns color selected by user.

 Default color is black.

Font

 Gets or sets Font

MaxSize , MinSize

 Starting and ending font size.

 Default values are 0 means, there are are no font size limits.

 Set

Output
ShowApply

 True or False

 Default value is False.

 If we wants to display ShowApply button then make it True.

ShowColor

 True or False

 The default value is False.

 Related with Color dialog combobox on FontDialog control.

ShowEffects

 Whether the dialog box contains controls that allow the user to specify
strikethrough, underline, and text color options.

 True or False.

 The default value is True.

If False 176
Example: On click of button open font dialog and apply effect.

Output

Private Sub btnFontDg_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnFontDg.Click

With FontDialog1

If .ShowDialog = Windows.Forms.DialogResult.OK Then

RichTextBox1.Font = .Font

RichTextBox1.ForeColor = .Color

End If

End With

End Sub

177
OpenFileDialog

It allows us to select a file to be opened.

Property Window

Some Properties of the OpenFileDialog:

CheckFileExists

 Boolean value.

 The default value is True.

 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

If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

MsgBox(OpenFileDialog1.FileName, MsgBoxStyle.Information, "File")

End If

End Sub

Filter property

 Related with "Files of type" drop-down


listbox.

 It is commonly used in all the software.

 For example, in Winamp if we click on open


File then it will not display .doc,.exe,.txt,.xls
etc. File type.

 Same for Microsoft Word, Microsoft


Excel,etc. software they all are display
related extension files only.

 With the help of Filter property we can set


this concept in OpenFile dialog
control.

 Format of it like "User understand title|*.extension"

Exampled: Design time

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

Private Sub btnFileOpen_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnFileOpen.Click

OpenFileDialog1.Filter = "Text Files|*.txt|Word file|*.doc|All files|*.*"

If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

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

OpenFileDialog1.Filter = "GIF images|*.gif|JPG images|*.jpg|BMP


images|*.bmp"

If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

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.

 By default index 1 is display.

Example:

If we write

OpenFileDialog1.Filter = "GIF images|*.gif|JPG images|*.jpg|BMP images|*.bmp"

Then

GIF images|*.gif have index no 1.

JPG images|*.jpg have index no 2.

BMP images|*.bmp have index no 3.

And if we set OpenFileDialog1.FilterIndex = 2 then whenver we open the


OpenFileDialog it will display first JPG images in the Files of type list box.

InitialDirectory property

 Gets or sets a initially display directory of OpenFileDialog dialog

Example: Whenever user will click on Open C: will first display

With OpenFileDialog1

.InitialDirectory = "c:\"

If .ShowDialog() = DialogResult.OK Then


Logic…
End If

End With

182
ReadOnlyChecked

 Boolean value.

 Whether the read-only check box is selected on the dialog box.

ShowReadOnly

 Boolean value.

 Whether the dialog box contains a read-only checkbox.

Title property

 Gets or sets title of the OpenFile dialog box.

Example:

OpenFileDialog1.Title = "Hai Hello"

SaveFileDialog

Allow us to save the file in a specified location.

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.

Examples: Save file using SaveFileDialog control.

183
Private Sub btnFileSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFileSave.Click

With SaveFileDialog1

.Filter = "Text files|*.txt"

If .ShowDialog = Windows.Forms.DialogResult.OK Then

RText.SaveFile(.FileName, RichTextBoxStreamType.PlainText)

End If

End With

End Sub

184
RichTextBox Control

 It's an advance version of TextBox.

 Difference between TextBox and RichTextBox is like Notepad and WordPad.

 It provides more advanced text formatting option.

 It can load RTF ,TXT format files for reading or editing.

 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.

 By default RichTextBox is multiline.

 By default maxlength of it 2147483647.

 Some properties of RichTextBox are


BulletIndent,ZoomFactor,SelectionFont,SelectionColor ,Alignment, etc.

 Methods of RichTextBox are like


LoadFile,SaveFile,Cut,Copy,Paste,Undo,Redo,Replace, etc.

 We are going to create Notepad, during it we can learn the advance features of
RichTextBox.

Example: Create notepad with menus as given below:

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

If Me.Text <> "Notepad" Then

richTxt.SaveFile(Me.Text, RichTextBoxStreamType.PlainText)

MsgBox("Your file is saved", MsgBoxStyle.Information, "Notepad")

Me.Text = "Notepad"

richTxt.Clear()

Else

End If

End Sub

Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles OpenToolStripMenuItem.Click

'Open

With OpenFileDialog1

.Filter = "Text file|*.txt|RTF file|*.rtf"

If .ShowDialog = Windows.Forms.DialogResult.OK Then

richTxt.LoadFile(.FileName, RichTextBoxStreamType.PlainText)
Me.Text = .FileName

End If

End With

End Sub

Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles SaveToolStripMenuItem.Click

'Save

If Me.Text = "Notepad" Then

With SaveFileDialog1

.Filter = "Text file|*.txt|RTF file|*.rtf"


.Title = "Save file"

If .ShowDialog = Windows.Forms.DialogResult.OK Then

richTxt.SaveFile(.FileName, RichTextBoxStreamType.PlainText)

186
Me.Text = .FileName

End If

End With

Else

richTxt.SaveFile(Me.Text, RichTextBoxStreamType.PlainText)

MsgBox("Your file is saved", MsgBoxStyle.Information, "Notepad")

End If

End Sub

Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles SaveAsToolStripMenuItem.Click

'Save As

With SaveFileDialog1

.Filter = "Text file|*.txt|RTF file|*.rtf"

If .ShowDialog = Windows.Forms.DialogResult.OK Then

richTxt.SaveFile(.FileName, RichTextBoxStreamType.PlainText)

Me.Text = .FileName

End If

End With

End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ExitToolStripMenuItem.Click

End

End Sub

Private Sub UndoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles UndoToolStripMenuItem.Click

richTxt.Undo()

End Sub

Private Sub RedoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RedoToolStripMenuItem.Click

richTxt.Redo()

187
End Sub

Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CutToolStripMenuItem.Click

richTxt.Cut()

End Sub

Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CopyToolStripMenuItem.Click

richTxt.Copy()

End Sub

Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles PasteToolStripMenuItem.Click

richTxt.Paste()

End Sub

Private Sub SelectAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles SelectAllToolStripMenuItem.Click

richTxt.SelectAll()

End Sub

Private Sub SelectedToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles SelectedToolStripMenuItem.Click

'Font->Selected

With FontDialog1

If .ShowDialog = Windows.Forms.DialogResult.OK Then

richTxt.SelectionFont = .Font

End If

End With

End Sub

Private Sub AllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles AllToolStripMenuItem.Click

'Font->All

With FontDialog1

If .ShowDialog = Windows.Forms.DialogResult.OK Then

188
richTxt.Font = .Font

End If

End With
End Sub

Private Sub SelectedToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles SelectedToolStripMenuItem1.Click

'Color->Selected

With ColorDialog1

If .ShowDialog = Windows.Forms.DialogResult.OK Then


richTxt.SelectionColor = .Color
End If

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

If .ShowDialog = Windows.Forms.DialogResult.OK Then


richTxt.ForeColor = .Color
End If

End With

End Sub

Private Sub RightToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles RightToolStripMenuItem.Click

richTxt.SelectionAlignment = HorizontalAlignment.Right

End Sub

Private Sub LeftToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles LeftToolStripMenuItem.Click

richTxt.SelectionAlignment = HorizontalAlignment.Left

End Sub

Private Sub CenterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CenterToolStripMenuItem.Click

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

Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ToolStripMenuItem2.Click

richTxt.ZoomFactor = 2

End Sub

Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ToolStripMenuItem3.Click

richTxt.ZoomFactor = 5

End Sub

Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ToolStripMenuItem4.Click

richTxt.ZoomFactor = 10

End Sub

Private Sub AboutMeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles AboutMeToolStripMenuItem.Click

Dim frm As New frmDialog1


frm.ShowDialog()

End Sub

190
TreeView Control

 It display a hierarchy of nodes both parent and child.

 Windows Explorer and Solution Explorer contain TreeView control.

 TreeView control is collection of nodes.

 The main starting node is called root node.

 Under the root, a real tree is made of branches and leaves.

 A node can have a node as a child.

 We can expand and collapse these nodes by clicking them.

 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

TreeView have nodes collection.

Properties of Nodes collection

Count – It returns total number of elements or say nodes in the TreeView.

Example: MsgBox(tvHMall.Nodes.Count)

Items – It returns the nodes of the given index.

Example:

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles btnAns.Click

Dim node As New TreeNode

node = tvHMall.Nodes.Item(1)

MsgBox(node.Text)

End Sub

Methods of Nodes collection Output


Add() – It adds nodes in the TreeView.

Example:

tvHMall.Nodes.Add("Mumbai")

Example:

With tvHMall.Nodes
.Add("Mumbai")

192
.Add("Noida")
.Add("Delhi")
.Add("Ahmedabad")
End With

Example:

Dim Item_name As String

Item_name = InputBox("Enter Item", "")

tvHMall.Nodes.Add(Item_name)

AddRange()- It adds nodes array

Example:

Dim strNodes(2) As TreeNode

strNodes(0) = New TreeNode("Juhu")


strNodes(1) = New TreeNode("Malad")
strNodes(2) = New TreeNode("Ghatkopar")

tvHMall.SelectedNode.Nodes.AddRange(strNodes)

Clear() – It clears all the nodes from the TreeView.

Example: tvHMall.Nodes.Clear()

Contains()

It returns Boolean answer.

It checks whether the given node is a part of TreeView or not.

Example:

Dim node As New TreeNode


node.Text = "Nano"

If tvCar.Nodes.Contains(node) = True Then


MsgBox("Yes")
Else
MsgBox("False")
End If

Insert()

It contains 2 arguments. Index and Node.

We can insert node in the Treeview in any place by using Insert method.

Example:

Dim node As New TreeNode

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)

RemoveAt() – It removes the node from the TreeView by index.

Example: tvCar.Nodes.RemoveAt(0)

How can we identify the selected node and child node?

Selected Node

Private Sub btnSel_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnSel.Click

MsgBox(tvCities.SelectedNode.Text)

End Sub

Private Sub btnChi_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnChi.Click

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)

In above image the sequence of the nodes as given below:

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.

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAdd.Click

tvHMall.Nodes.Add(txtData.Text)

End Sub

Private Sub btnChild_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnChild.Click
tvHMall.SelectedNode.Nodes.Add(txtData.Text)

End Sub

Private Sub btnRemove_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
btnRemove.Click

tvHMall.SelectedNode.Remove()

End Sub

Private Sub btnClear_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles btnClear.Click

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

Private Sub btnExp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnExp.Click

tvHMall.ExpandAll()

End Sub

Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCount.Click

MsgBox(tvHMall.Nodes.Count)

End Sub

CheckBoxes

 True or False

195
 Display checkbox with TreeView‘s node.

 Default value is False.

HotTracking

 True or False

 Default value is False.

 Nodes get hyperlink effect when the mouse is moved over them.

ShowLines

 True or False

 Default value is True.

 Whether the lines are displayed between


nodes or not.

ShowPlusMinus

 True or False

 Default value is True.

 Whether the Plus/Minus symbol


displayed or not.

ShowRootLines

 True or False

 Default value is True.

 Whether the Rootlines are displayed


between parent / child nodes or not.

FullPath

 It returns full path of the node.

Example:

MsgBox(tvHMall.SelectedNode.FullPath)

BCA\GLS

PathSeparator

 The string delimeter used for path returnd by FullPath property.

 The default value is \.

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:

Step 1: Add ImageList control to our form.

Step 2: Go to Images property of ImageList control and add images in it.

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

Step 4: Now run the project and see the effect.

197
ListView Control

It‘s an advanced ListBox.

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.

ListView have Items collection like ListBox.

We can add items at design time using Items editor.For it click on Items property.

198
Coding:

Private Sub frmListV_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

ListView1.View = View.Details

ListView1.Columns.Add("Director", 40, HorizontalAlignment.Left)


ListView1.Columns.Add("Movie", 40, HorizontalAlignment.Left)
ListView1.Columns.Add("Review", 40, HorizontalAlignment.Left)

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

Private Sub cmbView_SelectedIndexChanged(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles cmbView.SelectedIndexChanged

Dim str As String


str = cmbView.Text

If str = "small" Then


ListView1.View = View.SmallIcon
ElseIf str = "Large" Then

199
ListView1.View = View.LargeIcon
ElseIf str = "Details" Then
ListView1.View = View.Details
Else
ListView1.View = View.List
End If
End Sub

Events of the ListView are SelectedIndexChanged,ColumnClick,ItemCheck,etc.

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.2 Answer the following:

1. Explain check State property of checkbox with its example.


2. Explain GropuBox and Panel.
3. Explain text manipulation and text selection properties of textbox.
4. Explain SelectedIndex and SelectedIndices properties of the ListBox.
5. Write down the formula of Scrollbar can scroll.
6. Explain all the Common dialog control.
7. Explain the use of PathSeparator and FullPath property of TreeView control.

Q.3 Compare

1. CheckBox and Radio Button


2. Valuechanged event and Scrollevent of ScrollBar
3. Groupbox and Panel
4. ComboBox and ListBox
5. TextBox and RichTextBox.

Q.4 Write down coding:

1. How can we count the total number items in the list?


2. Explain as possible ways add items in the list and remove items from the list.
3. add and insert method of Listbox
4. Give example selectionmode property of Listbox.
5. Give example of DropDownStyle of comboBox.
6. Explain the difference between getselected, setselcted and clearselected methods
of listbox.
7. Load file in the RichTextBox control.
8. Save file in the RichTextBox control.
9. Give example of Filter property of FontDialog.
10. Count total number of nodes in the TreeView control.

Q.5 Write down True or False.

1. We can have mutliline textbox with password.


2. The default size of textbox is 20000.
3. Bydefault we can select multiple items in the ListBox.
4. ComboBox have columns property.
5. The default dropdown style property set as simple.
6. By default Font dialog control display color selection area.
7. We can identify the selected node by node property.

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.

2. Create form as given below:

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.

5. According to Trackbar‘s position the Table 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.

7. Redefine program no.2 with the 2nd picture box.

8. Redefine program no.2 with 3 textboxes.

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.

11. According to scrollbar position the Table will display.

12. Redefine program no.8 with the 2nd picture box.

13. Redefine program no.2 with 3 textboxes.

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.

15. Print ABCD according to position.

Combo Box

16

17 Take 2 comboboxes.Store rollno in one combobox and store name in second


combobox. If we change the rollno the corresponding name will appear in the second
combobox. (Viceversa)

18 Create money conversion program as given below:

203
ListBox

19 Listbox name is lstBox and righthand side listbox name is lstmode

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

22.Display only CheckedItem

23. Display items state whether checked or not

24. Find item by entering string if found then select it.

206
25

OnClick of Inbox button one Item must be added.


OnClick of Delete button ask to the user ―Do you want to delete or not?‖, if user press
yes then selected Items must be deleted.
OnClick Read Button the selected item display in the messagebox(―Hello‖ & Selected
item name)

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

Create notepad using RichTextBox and Common dialog control.

29 Take 2 treeview controls , one textbox, 2 radiobuttons and 1 button. If we select


radiobutton country then entered value in the textbox should be added in the treeview1
else

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.

 As given in above image Data Functions protects Data Members.

 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.

 The main benefit of OOP is resuablility.

210
Overview of basic concepts of OOP:
Classes

 A class is a collection of objects of similar type.

 Class describes the structure of objects.

 Once a class is defined, any number of objects can be created which belong to
that class.

Objects

 Objects are the basic run-time entities in an object-oriented system.

 It is an instance of the class.

 Each instance is distinct copy of its class.

 Meet, Rajal, Kevin are objects of Student class.

 Dove, Duck, Swan, Sparrow are objects of Bird class.

 In VB.NET Form and controls are objects.

 A class is a blueprint or model on paper, and an object is a building based on that


blueprint or model.

Polymorphism

 Polymorphism means the ability to take more than one form.

 One name many form is called Polymorphism.

 In Om shanti om, shahrukh khan is an example of Polymorphism. The name of


Actor is shahrukh khan but forms are 2. One is Om makihja and second is Om
kapoor.

 There are 2 types of Polymorphism Runtime and Design Time.

 Function overloading is an example of Design time polymorphism.

Encapsulation

 Storing data and functions in a single unit (class) is encapsulation.

 Class is the best example of it.

Data Abstraction

 Focusing on the essential data without including background details.

 Abstraction refers to the act of representing essential features without including


the background details or explanations.

211
Inheritance

 Inheritance means heredity. Some of the charactersitics of son or daughter are


common to their parents.

 Inheritance means create new classes based on an existing class.

 The new class will have combined features of both the classes.

 It provides reusability.

Advantages of OOP

Object-Oriented Programming has the following advantages:

 Programs are divided into small objects.

 Programmers can work easily on objects.

 Work can divide between programmers.

 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.

 OOP provides a good framework for create code libraries.

 It follows bottom-up approach

212
Let‘s start with the example of Class

We can add new class by

1. Right Click on Solution Explorer Add ->New Item

2. Right Click on Solution Explorer ->Class


3. Project Menu->Add class

Example: Class demo

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.

Right down coding in the button click event.

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:

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAns.Click

Dim obj As New clsMath


obj.setData(txtNo.Text) Output
MsgBox(obj.Display())

End Sub

214
Property
 A Property procedure is the 4th type of procedure.

 It is also known as property accessors.

 Property procedures are executed when the property value is set or retrieved.

 In C++ we create SetData() and PrintData() data functions instead of that in


VB.NET we create Property.

 A property does not have any storage location.

 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.

 We create property usually per data member.

 There are 3 types of property read-only, write-only, or read/write. The default is


read/write.

Syntax:

[accessibility] Property propertyname[(argumentlist)] As datatype

Get
Return varName
End Get

Set [(ByVal newvalue As datatype)]


varName = newvalue
End Set

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:

Public Class clsStu

Dim m_no As Integer


Dim m_name As String

‗Take datamember name whatever but write property name proper.

Property Rollno() As Integer

Get
Return m_no
End Get

Set(ByVal value As Integer)


m_no = value
End Set

End Property

Property StuName() As String

Get
Return m_name
End Get

Set(ByVal value As String)


m_name = value
End Set

End Property

End Class

Properties are Public by default, which means we can call them from anywhere in our
application.

The hand icon indicates the property.

216

Coding Window
Dim obj As New clsStu

obj.Rollno = 5
obj.StuName = "Suresh Rathod"

MsgBox(obj.Rollno)
MsgBox(obj.StuName)

Property procedures contains 2 area

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"

 Above lines will set the datamembers.

 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.

We can also put the restrictions

Property Age()As Integer

Get
Return m_Age
End Get

Set(ByVal Value As Integer) 'We want to put criteria in Age

If Value > 18 And Value < 50 Then


m_Age = Value
Else
m_Age = 0
End If
End Set

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).

Read-Only and Write-Only Properties

 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.

 For example, average speed of a bike, name of the company.

 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.

 For example, password.

Example:

Public Class clsStu

Dim m_no As Integer


Dim m_name As String
Dim m_pwd As String

Property Rollno() As Integer

Get
Return m_no
End Get
Set(ByVal value As Integer)
m_no = value
End Set

End Property

Property StuName() As String

Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set

End Property

ReadOnly Property CollegeName() As String

Get
Return "LJ CCA"
End Get

End Property

WriteOnly Property Password() As String

Set(ByVal Value As String)


m_pwd = Value
End Set

218
End Property

End Class

Write down below coding in the btnAns click , code will generate error.

CollegeName is Readonly property.

Password is Writeonly property.

So, this code is wrong.

Coding Window

Right coding

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim obj As New clsStu

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".

 There are 2 types of it Design time and Run time.

 Design time polymorphism is achieved by function overloading and Run time


polymorphism is achieved by function overriding.

 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:

Public Class clsMath

Function add(ByVal i As Integer) As Integer

'function with one argument

Return I

End Function

Function add(ByVal i As Integer, ByVal j As Integer) As Integer

'function with two arguments

Return i + j

End Function

Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer

'function with three arguments

Return i + j + k

End Function

End Class

Create object of the class and call functions

We can easily get the effect of the function


overloading. 1 of 3 means total 3 functions
are declared and this one is 1st one.

Coding Window

220
Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAns.Click

Dim obj As New clsMath

msgbox(obj.add(10))

msgbox(obj.add(10, 20))

msgbox(obj.add(10, 20, 30))

End Sub

221
Inheritance

 Inheritance means create new classes based on an existing class.

 The new class will have combined features of both the classes.

 It is also known as a generalization.

 Multiple classes may inherit from a single base class.

 Inheritance represents ―is-a‖ relationship. Abhishek bachchan is a son of Amitabh


bachchan.

 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.

 All classes are inheritable by default.

There are 3 modifiers related with inheritance as given below:

 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:

Public Class A „Parent class

Logic…………………

End class

Public class B „Child class


Inherits A

Logic……………………

End class

Example: Create Class employee having empname, post, salary as properties.


Create one derive class Extra give bonus to employee. Calculate salary and
display in the GUI interface.

Popup box contains list


of class for inherit

Base class

223

Derived class
Coding Window Windows Form

Create the object of derived class in the form.

See the magic object of clsExtra contains base class clsEmp‘s properties.

Always rember that

Derived class object‘s contains = Base class‘s data members +data functions + Dervied
class‘s data members + data functions

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim obj As New clsExtra

obj.Name = txtName.Text
obj.Post = txtPost.Text
obj.Salary = txtSal.Text
obj.Bonus = txtBonus.Text

txtAns.Text = (obj.Salary * 12) + obj.Bonus

End Sub

Output

224
NotInheritable
 It is also known as sealed class.

 If we write NotInheritable keyword in class then no other classes can be derived


from this 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:

Public NotInheritable Class Emp

End Class

 When this keyword is used, no other code may use the Inherits keyword to create
a subclass of our class.

It‘s depends on requirement application or requirement whether to create class as a


NotInheritable or not.

Example: Create class clsA as NotInheritable and try to derive it in clsB

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.

 It provides Skelton to the derived class.

 It has no actual code.

 An abstract class is the one that is not used to create objects.

 Abstract class is a design concept in program development and provides a base


upon which other classes are built.

 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:

Public MustInherit Class className

Logic………

End Sub

Example:

MustInherit class clsAbs1

Coding Window

Write class name and then press Enter key

226
Coding Window

Methods written in above class as MustOverride are automatically appear in the derived
class.

MustOverride

 It indicates that the specified method or property has to be implemented in the


derived class.

 No other statements are allowed, and specifically there is no End Sub or End
Function statement.

 MustOverride methods must be declared in MustInherit classes.

 If your class contains any one method as a MustOverride keyword then your class
must have MustInherit keyword.

 MustOverride methods autatically appears in the derived class we should keep in


the derived class other wise it will generate error.

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.

Public MustInherit Class clsPoly

Dim m_H, m_W As Double

Public Property Height() As Double


Get
Return m_H
End Get
Set(ByVal value As Double)
m_H = value
End Set
End Property

Public Property Width() As Double


Get
Return m_W
End Get
Set(ByVal value As Double)
m_W = value
End Set
End Property

MustOverride Function Area() As Double

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:

Public Class clsTri


Inherits clsPoly

Public Overrides Function Area() As Double


Return 0.5 * Height * Width
End Function

End Class

Public Class clsRect


Inherits clsPoly

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

Public Class frmOOps

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAns.Click

Dim objTri As New clsTri


objTri.Height = txtTHeight.Text
objTri.Width = txtTWidth.Text
txtTArea.Text = objTri.Area

Dim objRect As New clsRect


objRect.Height = txtRHeight.Text
objRect.Width = txtWRect.Text
txtRArea.Text = objRect.Area

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.

 Derived class Inherits methods from its base class.

 If an inherited property or method needs to behave differently in the derived


class it can be overridden.We can define a new implementation of the method in
the derived class.

 The Overridable keyword is used to mark a function as overridable. We can


redefine overridable methods in derived class.

 The Overridable keyword is used when defining a property or method of an


inherited class, as overridable by the inheriting class.

 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 Overrides an Overridable property or method defined in


the base class.

 The Overides keyword allows the inheriting class to redefine the property or
method of the inherited class and implements its own code.

Example: Wrong coding

Base class clsA

Derived class clsB

230
Write Overridable keyword before
Function

Coding Window

Write Overrides keyword in derived class‘s Display method.

NotOverridable

 Prevents a property or method from being overridden in an inheriting class.

 Public methods are NotOverridable by default.

 Remember that we cannot write NotOverridable keyword.

 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.

 A Constructor is a special function which is called automatically when a class is


created.

 This is the first method that is run when an instance of a type is created.

 The name of the constructor is New().

 A constructor is invoked whenever an object of its associated class is created.

 Constructors can be overloaded, but unlike the functions, the Overloads


keyword is not required.

 There are 2 types of constructor: without argument and with argument.

Synatx:

Sub New()

End sub

The following code demonstrates the use of constructors in Visual Basic.

Public Class clsStu

Dim m_No As Integer


Dim m_Name As String
Dim m_Fees As Integer

Sub New()
Rollnumber = 5
NameofStu = "Vishwaraj"
Fees = 1000
End Sub

Sub New(ByVal n As Integer, ByVal nam As String, ByVal f As Integer)


Rollnumber = n
NameofStu = nam
Fees = f
End Sub

Public Property Rollnumber() As Integer


Get
Return m_No
End Get
Set(ByVal value As Integer)
m_No = value
End Set
End Property

Public Property NameofStu() As String


Get
Return m_Name

232
End Get
Set(ByVal value As String)
m_Name = value
End Set
End Property

Public ReadOnly Property CollegeName() As String


Get
Return "LJ BCA"
End Get
End Property

Public WriteOnly Property Fees() As Double


Set(ByVal value As Double)
m_Fees = value
End Set
End Property

Function print() As String


Return "Name = " & NameofStu & " No = " & Rollnumber & " College = " &
CollegeName
End Function

End Class

Coding in Form:

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim obj As New clsStu(1, "shyam", 10000)

lblNo.Text = obj.Rollnumber
lblName.Text = obj.NameofStu
lblCollegeName.Text = obj.CollegeName
lblPrint.Text = obj.print

End Sub

Private Sub btnAns2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAns2.Click

Dim obj As New clsStu()


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

And for parameterized

Sub New (parameter…….)

End Sub

Now will see demo of calling base class‘s constructor.

Example:

Public Class clsB 'Base class

Private x As Integer
Private y As Integer

Sub New()
x=0
y=0
End Sub

Sub New(ByVal a As Integer)


x=a
y=a
End Sub

Sub New(ByVal a As Integer, ByVal b As Integer)


x=a
y=b
End Sub

End Class

Public Class clsD 'Derive class


Inherits clsB

Private z As Integer

Sub New()

MyBase.New() ‗call base class‘s constructor without parameter


z=0

End Sub

Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)

MyBase.New(a, b) „call base class‘s constructor with parameter

234
z=c
End Sub

End Class

In the form:

Private Sub btnAns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles btnAns.Click

Dim objD As New clsD

Dim objD1 As New clsD(4, 6, 7)

End sub

MyBase keyword

 We can use the MyBase keyword to call methods in a base class.

 MyBase refers to the immediate base class and its inherited members.

 It cannot be used to access Private members in the class.

235
Destructors
 A Destructor is a special function which is called automatically when a class is
destroyed.

 A destructor, also know as finalizer, is the last method run by a class.

 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.

 Destructors cannot be overloaded.

 When an instance is destructed, the destructors in its inheritance chain are called,
in order, from most derived to least derived.

Syntax:

Overrides Protected Sub Finalize()


Logic..
End Sub

What is Garbage Collector or How VB.NET mange memory?

Garbage Collector can do better object release than we can.

 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 destroys the objects only when necessary.

 Some situations of necessity are memory is exhausted or user explicitly calls


System.GC.Collect() method.

 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.

 Interface represents ―has-a‖ relationship. Abhishek bachchan has a very beautiful


wife.

 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.

 We can implement multiple interfaces.

 If we want to use interface then we need to write ―Implements‖ keyword.

Syntax:

Public Interface nameofInterface

End Interface

Example:

Public Interface Iface1


Sub Show_A()
Property MyProp(ByVal MyStr As String)
Function MyFunc(ByVal MyInt As Integer) As Integer
End Interface

Example:

Public Class clsDemo


Implements Iface1 ‗press enter

logic…..

237
End class

Example: 2 interface and 1 class implements interfaces.

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

Interface Abstract class


A class may implement several A class may extend only one abstract
interfaces. class.
An interface cannot provide any code at An abstract class can provide complete
all, much less default code. code, default code, and/or just stubs that
have to be overridden.
Slow, requires extra indirection to find Fast
the corresponding method in the actual
class.
Does not contain constructor Yes
Does not have any variable Yes
Does not have mustoverride keyword Yes

Summary

Inherits

Indicates the class from which the new class inherits

NotInheritable

Indicates that a class that cannot be inherited from

MustInherit

Indicates a class that must be inherited by another class

Overridable

Indicates a procedure that can be overridden by a subclass

NotOverridable

Indicates a procedure that cannot be overridden in a subclass

MustOverride

Indicates a procedure that must be overridden in a subclass

Overrides

Indicates that a procedure is overriding a procedure in a base class

MyBase

Allows code in a class to invoke code in the base class

MyClass

Allows code in a class to invoke code in itself

239
How to work in Console base?

From Solution explorer add new Module and Write down this below coding in
module

System.Console is the namespace related with Console based application.

Then change 2 things


From Project
properties

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.

Example 2: Simple addition

Imports System.Console

Module Module1

Sub main()

Dim a, b As Integer
WriteLine("Enter no a ->")
a = ReadLine()

WriteLine("Enter no b ->")
b = ReadLine()

Dim ans As Integer


ans = a + b

WriteLine("Ans = " & ans)


Read()

End Sub
End Module

Example 3: Scan the data and print

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()

WriteLine("Name = " & name)


WriteLine("No = " & No)

Read()

End Sub
End Module

Example 4: Class and module like C++

Math Class contains following code

Public Class clsMath

Dim m_x, m_y As Integer

Property X() As Integer


Get
Return m_x
End Get
Set(ByVal value As Integer)
m_x = value
End Set
End Property

Property Y() As Integer


Get
Return m_y
End Get
Set(ByVal value As Integer)
m_y = value

242
End Set
End Property

Function Mul() As Integer


Return X * Y
End Function

End Class

Now add module and write create the object inside sub main() function.

Imports System.Console

Module Module1

Sub main()

Dim obj As New clsMath

obj.X = 5
obj.Y = 10

Dim ans As Integer


ans = obj.Mul()

WriteLine(ans)
Read()

End Sub

End Module

243
Array

 Arrays allow us to refer to a series of variables by the same name.

 It is a representation of data in contiguous area in the memory.

 Each element in the array is identified by the index.

 It‘s a very common concept for every programming language.

 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:

Dim ar(4) As Integer

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.

If we declare array with size 10 then we can store 11 items. (0-10)

We can use mix data types in an array if it is declared of type Object.

The following example stores employee information in the array variable EmployeeData.

Dim EmployeeData(3) As Object ' Allocates (0) through (3).


Dim i As Integer

EmployeeData(0) = "Miss Namrata B. Trivedi"


EmployeeData(1) = "10/20/1978"
EmployeeData(2) = 41
EmployeeData(3) = "10/10/2008"

For i = 0 To 3
TextBox1.Text &= EmployeeData(i) & vbCrLf
Next

244
Array Dimensions

An array can have one dimension or more than one.

we can specify up to 32 dimensions, although more than three is extremely rare.

Multidimensional Arrays

The following statement declares a two-dimensional array with 5 rows and 10 columns.

Dim myAr(4, 9) As Integer

(0) through (4), (0) through (9).

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 lowest subscript value for a dimension is always 0.

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

Dim MaxDim0, MaxDim1 As Integer

Dim Ar1(5, 5) As Double

MaxDim0 = Ar1.GetUpperBound(0)
'returns 5 from 1st dimension

MaxDim1 = Ar1.GetUpperBound(1)
'returns 5 from 2nd dimension

For I = 0 To MaxDim0

For J = 0 To MaxDim1 Coding Window


Ar1(I, J) = (I * 10) + J
Next J

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

We can set the value of array as possible as given below:

Dim ar(3) As String

ar(0) = "vedika"

245
ar(1) = InputBox("Enter value")

ar(2) = TextBox1.Text

ar.SetValue("hai", 3)

We can get the value from the array as given below:

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

 The length of an Array is the total number of elements it can contain.

Example:

Dim name(6) As String, nameLen(6, 4) As Integer

MsgBox(name.Length)
MsgBox(nameLen.Length)

Output:

7 [0-6]
35 [0-6 X 0-4 = 7X5 = 35]

GetLength

 It returns the number of elements in the specified dimension of the Array.

 An example of GetLength is GetLength(0), which returns the number of elements


that can be store in the 1st dimension of the Array.

 GetLength(1), which returns the number of elements that can be store in the 2nd
dimension of the Array.

Example:

Dim name1(6) As String, name2(5, 4) As Integer

MsgBox(name1.GetLength(0)) 'Returns 7
MsgBox(name2.GetLength(0)) 'Returns 6
MsgBox(name2.GetLength(1)) 'Returns 5

246
Rank

 It returns number of dimensions in the Array.

Example:

Dim name(6) As String

Dim mat(2, 2) As Integer

MsgBox(name.Rank)
MsgBox(mat.Rank)

The output of name.Rank is 1 and mat.Rank is 2

GetUpperBound

 Returns highest subscript(index)value of specified dimension in the Array.

GetLowerBound

 Returns lowest index of the specified dimension in the Array

Example:

Dim name1(6) As String, name2(6, 4) As Integer

MsgBox(name1.GetUpperBound(0) & ",‖ & name1.GetLowerBound(0))

MsgBox(name2.GetUpperBound(0) &",‖& name2.GetLowerBound(0))

MsgBox(name2.GetUpperBound(1) &",‖& name2.GetLowerBound(1))

Output:

1)Getupperbound = 6 GetLowerBound=0

2)Getupperbound = 6 GetLowerBound=0

3)Getupperbound = 4 GetLowerBound=0

Example: Mix All

Dim ar(1,2) as intger

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)

txtAns.Text &= Space(5) & ar(i, j)

Next

txtAns.Text &= vbNewLine


Output
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

 The clear method clears the array data

Array.Clear(name, 0, 1)

GetValue

 It returns the value of the particular index from Array.

Example:

Dim name(6) As String

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

 We can set value of particular element.

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

 Sorting method is overloaded. 7 methods are there.

Example: Normal Sorting

Private Sub btnSort_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSort.Click

Dim name(6) As String

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

Example 2: By Key according to length wise

Private Sub cmdSortLen_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs)
Handles cmdSortLen.Click

249
Dim i As Integer

Dim name(6) As String


Dim nameLen(6) 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

Example 3: Certain data sort 0 to 4 index only

Private Sub cmdSort3_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdSort3.Click

Dim name(6) As String


name(0) = "Yash"
name(1) = "Bijal"
name(2) = "Aalok"
name(3) = "Chandni"
name(4) = "Amish"
name(5) = "Ritu"
name(6) = "Alpesh"

ListBox1.Items.AddRange(name)
System.Array.Sort(name, 0, 4)
ListBox2.Items.AddRange(name)

End Sub
Output
Example 4: Search particular item

Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdSearch.Click

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"

search_item = Trim(InputBox("Enter search item"))

‗Index of start search starting of the array

i = System.Array.IndexOf(name, search_item, 0)

txtIndex.Text = i

End Sub

Example 5: Reverse order

Dim name(6) As String

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

Array.Copy(sourceArray, destinationArray, length)

 It copies a range of elements from one array to another.

 The sourceArray and destinationArray parameters must have the same number of
dimensions.

Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex,


length)

 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:

Dim name(6), name2(6) As String

name(0) = "Yash"
name(1) = "Maitri"
name(2) = "Aalok"

name.CopyTo(name2, 0)

What is dynamic array? or Resizing Arrays (IMP)


 In any C or C++ we can not modify the size of the array. Ones we declare array
with its size then it is fixed.

 In VB.NET we can increase the size of the array.

 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.

 We can resize an array at any time by using ReDim keyword.

 We can not modify the dimension of the array.

Example:

Dim tmpArray() As Integer

Dim cnt As Integer

cnt = CInt(InputBox("Enter size"))

ReDim tmpArray(cnt)

MsgBox(tmpArray.Length)

 This helps you manage memory efficiently.

 We can use a large array for a short time and then ReDim it to a smaller size. It
frees the memory.

Example:

Dim Rollno(2) As Integer

Form_Load

Rollno(0) = 1
Rollno(1) = 2

252
Rollno(2) = 3

End sub

 When we ReDim an array, its existing values are normally lost.

 VB.NET resets all the values to their default initial values.

 It resets numeric elements to 0 and string elements to empty strings.

Example: Problem

Output

Private Sub Before_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Before.Click

Dim i As Integer

For i = 0 To Rollno.GetUpperBound(0)
lstNo.Items.Add(Rollno(i))
Next

End Sub

Wrong one

Private Sub After_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles After.Click

Dim i As Integer

ReDim Rollno(10) „Loss the value

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

Private Sub After_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles After.Click

Dim i As Integer

ReDim Preserve Rollno(10)

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.

Collection contains in which values of mixed data types can be placed.

Collections are increased in size simply by adding items to it.

It‘s like linklist in DFS.

The collections are part of the System.collection class.

Below table represents some of the collection.

Class Description

ArrayList Whose size is dynamically increased as required.

Hashtable Represents a collection of key/value pairs.

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.

The following statement declares a collection of citites.

Dim Cities As New Collection

The collection have Add method, Remove,RemoveAll,Contains,etc. methods, Count ,


Item,etc. properties.

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.

 It implements IList interface.

 It can grow dynamically; we can add elements in it at runtime.

 Array is for homogeneous data. i.e data of same data type.

 Whereas Arraylist is for Heterogeneous data.The data in the arraylist need not be
of same data type.

 There is no restriction on the type of objects which can be added to an arraylist.

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.

 It‘s only one dimension.

The problems with Array are:

 It does not have dynamic structures.


 Resizing the array is a time-consuming operation.
 No simple method to insert additional elements or delete elements anywhere in
the array.
 To remove an item we have to move one by one and next item is shifted to that
removed item.
 If inserting element on first position then all elements are move next.
 An Array can have multiple dimensions, while an ArrayList or a List always has
exactly one dimension.
 Insert , delete problem.
 To access any element we must know index.

Properties of ArrayList

Capacity

 The capacity of an ArrayList is the number of elements the


Arraylist can hold.

 Capacity and Count is different property.

 As elements are added to an ArrayList, the capacity is


automatically increased.

 When we remove an item it‘s not decreased automatically. The


capacity can be decreased by calling TrimToSize or by setting the
Capacity property explicitly.

Example:

Private Sub frmArrayList_Load(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles MyBase.Load

Dim ar As New ArrayList ‗creating

ar.Capacity = 100

End sub

Count

 Count means total number of elements stored currently in the ArrayList.


Properties & Methods
Example:

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()

Dim str(4) As String


str(0) = "a"
str(1) = "b"
str(2) = "c"
str(3) = "d"
str(4) = "e"

ar.AddRange(str)

End Sub

Item

 It returns the value stored in particualr index.

Example:

Msgbox(ar.Item(0))

Example:Print with For…loop

Private Sub cmdPrintFor_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdPrintFor.Click

Dim i As Integer

For i = 0 To ar.Count - 1
txtPrint.Text &= ar.Item(i) & vbCrLf
Next

End Sub

Example:Print with for.. each

Dim str as string

For Each str In ar


txtPrint.Text &= ar.Item(i) & vbCrLf
Next

Methods of ArrayList

Add()

257
 It adds the elements in the ArrayList.

Example:

Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdAdd.Click

ar.Add("Karna")
ar.Add("Bhavin")
ar.Add("Trivedi")
ar.Add("Vedika")
ar.Add("Shyam")
ar.Add("Chawda")

MsgBox(ar.Count)

End Sub

AddRange

 It adds collection in the ArrayList as above AddArrayRange() sub procedure in


the example.

Clear

 It clears all the elements of ArrayList.

Example:

Ar.clear()

Contains

 Returns Boolean value.

 It determines that whether an element is in the ArrayList or not.

GetRange

 It retruns range of elements specified by the argument.

Example:

Dim ar As New ArrayList

Dim str As String

ar.Add("a")
ar.Add("b")
ar.Add("c")
ar.Add("d")
ar.Add("e")

Dim ar2 As New ArrayList

ar2 = ar.GetRange(0, 3) 'Copy from 0 to 2


Output

258
For Each str In ar
ListBox1.Items.Add(str)
Next

For Each str In ar2


ListBox2.Items.Add(str)
Next

Insert

 It inserts an element to the specific position

Example:

Dim ar As New ArrayList

ar.Add("a")
ar.Add("b")
ar.Add("e")

ar.Insert(2, "c") Output

For Each str In ar


ListBox1.Items.Add(str)
Next

InsertRange

 It inserts collection to the specific index.

Example:

Dim ar As New ArrayList

Dim str As String

ar.Add("om")
ar.Add("shanti")
ar.Add("om")

For Each str In ar


ListBox1.Items.Add(str)
Next

Dim strArr(4) As String

strArr(0) = "a"
strArr(1) = "b"
strArr(2) = "c"
strArr(3) = "d" Output
strArr(4) = "e"

ar.InsertRange(2, strArr)

For Each str In ar


ListBox2.Items.Add(str)
Next

259
Reverse

 It reverses the elements of ArrayList.

Example:

Dim ar As New ArrayList

ar.Add("a")
ar.Add("b")
ar.Add("c")
ar.Add("d")
ar.Add("e")

For Each str In ar


ListBox1.Items.Add(str)
Next

ar.Reverse()

For Each str In ar


ListBox2.Items.Add(str)
Next
Output

Remove, RemoveAt, RemoveRange

 Remove method remove element from the arraylist by its value.


 RemoveAt removes element by its position
 RemoveRange removes elements by given range.

Example:

ar.Remove("d")
ar.RemoveAt(2)
ar.RemoveRange(0, 2)

Sort

 It sorts the elements of ArrayList.

Example:

Dim ar As New ArrayList

ar.Add("Azad")
ar.Add("Suresh")
ar.Add("Anita")
ar.Add("Trupti")
ar.Add("Shanu")
ar.Add("Pooja")
ar.Add("Shweta")

For Each str In ar


ListBox1.Items.Add(str)
Next

Output 260
ar.Sort()

For Each str In ar


ListBox2.Items.Add(str)
Next

TrimtoSize

 It performs operation like ArrayList.capacity=ArraList.capacity-


ArrayList.count.

 It free up all the unused memory in the ArrayList.

Example:

ar.TrimToSize()

261
Exercise 6

Q1 Answer the following:

1. Explain OOP with its advantages.


2. Explain the concept of data encapsulation and data abstraction.
3. What is class? Explain with example.
4. What is object? Is it possible object without class? Explain with example.
5. What is data member and data function?
6. What is property procedure? Explain with its types and examples.
7. Explain Get and Set area of property procedure.
8. What is function overloading and function overriding? Explain with example.
9. What is constructor? Explain the different types of constructor with example.
10. What is Garbage collection or Destructor? How can we create destructor?
11. What is shared variable and instance variable?
12. What is an interface? What is the requirement of it?
13. Explain
a. Console.Write and Console.writeline
b. Console.Read and Console.readline

14.Which of the following statement creates object

a. Dim obj as new class_name


b. Dim obj as class_name

Q.2 Define the following keywords

1. Overriadable
2. Overrides
3. Must Override
4. Must Inherit
5. Mybase
6. My class
7. Not inheritable

Q.3 Write down True or False

1. Property procedure is by default false.


2. Property procedure is by default write only.
3. Class and object occupies memory.
4. Class does not have visible interface.
5. We can inherit more than one mustinherit class.
6. The meaning of mustinherit class and abstract class are same.
7. We can use the interface with in the class by inherits keyword.

Q.4 Practical List:

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

You might also like