Vous êtes sur la page 1sur 133

Programming in VB.

NET

Rohit Birla
RohitKumarBirla@gmail.com
RohitBirla_rb@yahoo.com
Your Success, Our Strength TM

Rohit Birla
RohitKumarBirla@gmail.com
RohitBirla_rb@yahoo.com

2
Your Success, Our Strength TM

Preface
It gives me great pleasure in presenting this book. “Programming in VB.NET” is
written with several goals in mind. It is designed to cover all essential and basic
information you will need to start your programming in VB.NET.

I hope this book will help you to start your programming in .NET.

In spite of all efforts some errors might be there. I shall be grateful to the
readers if the same are brought to my notice. Suggestions and comments for
further improvements of the book will be gratefully acknowledged.

June 29, 2010

Rohit Birla
RohitKumarBirla@gmail.com
RohitBirla_rb@yahoo.com

3
Your Success, Our Strength TM

About the Author:

Rohit Birla; is a student, currently perusing MCA. His area


of interest includes Operating System Development and
Windows Application Development.

He is also the author of

- Let’s make Linux together


- Program your Linux
- Review VB6.0(Part-1)

4
Your Success, Our Strength TM

Dedicate to

The person who had given me the name `Rohit`

5
Your Success, Our Strength TM

About the book:

This book is designed especially for .NET beginners. Some


of the main features include:

 A Totally programming approach


 Theory is kept to its minimum
 Every Topic is covered with Example
 Bundle of Assignments
 No Syntax Errors, Every code is shown as Screen-
Shot

Before you start .NET, I expect you are comfortable with


OOP concepts and VB Language.

6
Your Success, Our Strength TM

Contents:

PREFACE ................................................................................................................................................................ 3

ABOUT THE AUTHOR: ............................................................................................................................................ 4

ABOUT THE BOOK: ................................................................................................................................................. 6

CONTENTS: ............................................................................................................................................................ 7

.NET HISTORY ...................................................................................................................................................... 14

.NET HISTORY .............................................................................................................................................................14

APPLICATIONS THAT CAN BE DEVELOPED UNDER .NET ........................................................................................ 14

VISUAL STUDIO INTEGRATED DEVELOPED ENVIRONMENT .................................................................................. 14

WHY TO USE VS IDE ....................................................................................................................................................14

TYPES OF APPLICATIONS ...................................................................................................................................... 15

SINGLE TIER APPLICATIONS: ............................................................................................................................................15


TWO TIER APPLICATIONS: ..............................................................................................................................................15
 FAT CLIENT: .......................................................................................................................................................15
 FAT SERVER: .......................................................................................................................................................15
 DIVIDING BUSINESS SERVICES BETWEEN USER AND DATA SERVICES: ................................................................................15
LIMITATIONS OF TWO TIER APPLICATIONS: .........................................................................................................................16
THREE TIER APPLICATIONS:.............................................................................................................................................16
N – TIER APPLICATIONS: ................................................................................................................................................ 16

WHY TO USE .NET ................................................................................................................................................ 17

ADVANTAGES OF USING .NET FRAMEWORK ......................................................................................................................17

.NET ARCHITECTURE ............................................................................................................................................ 17

LAYER 1: ....................................................................................................................................................................18
LAYER 2: ....................................................................................................................................................................18
LAYER 3: ....................................................................................................................................................................18
MANAGE CODE ...........................................................................................................................................................18
GARBAGE COLLECTION PROCESS .....................................................................................................................................18
NAMESPACES: .............................................................................................................................................................19
ASSEMBLY: .................................................................................................................................................................19

MANAGE CODE EXECUTION PROCESS .................................................................................................................. 20

EXPLANATION: .............................................................................................................................................................20

FIRST VB.NET PROGRAM...................................................................................................................................... 21

HELLO WORLD AGAIN!!! ...............................................................................................................................................21

SECOND VB.NET PROGRAM ................................................................................................................................. 23

THIRD PROGRAM (USING STRUCTURES) .............................................................................................................. 24

7
Your Success, Our Strength TM

USING IF-ELSE ...................................................................................................................................................... 25

USING CONDITIONAL OPERATOR ......................................................................................................................... 25

LOOPING.............................................................................................................................................................. 26
Assignment: ...................................................................................................................................................................... 26

DEFINING ARRAYS & FOR-EACH LOOP ................................................................................................................. 27

SUBROUTINE VS. FUNCTION ................................................................................................................................ 27

DEFINITION OF SUBROUTINE AND FUNCTION ......................................................................................................................28

MULTI DIMENSION ARRAYS ................................................................................................................................. 28

RETRIEVING LOWER AND UPPER BOUND ............................................................................................................................28


Assignment ....................................................................................................................................................................... 28

USING SELECT-CASE ............................................................................................................................................. 29

FUNCTION OVERLOADING ................................................................................................................................... 29


Assignment ....................................................................................................................................................................... 30

DEFINING CLASSES ............................................................................................................................................... 30

MAKING A SIMPLE CLASS................................................................................................................................................30


CREATING CONSTRUCTOR...............................................................................................................................................31
OVERLOADING CONSTRUCTOR ........................................................................................................................................32
DEFINING PROPERTIES...................................................................................................................................................33

OPERATOR OVERLOADING .................................................................................................................................. 34


Assignment ....................................................................................................................................................................... 34

INHERITANCE ....................................................................................................................................................... 35

CODE REUSABILITY ........................................................................................................................................................35


TYPES OF INHERITANCE ..................................................................................................................................................35
VARIABLE SCOPE ..........................................................................................................................................................35
HOW TO INHERIT..........................................................................................................................................................35

RUN TIME POLYMORPHISM ................................................................................................................................. 37

OBJECT SLICING, RUN TIME BINDING, LATE BINDING...........................................................................................................37


EXAMPLE ....................................................................................................................................................................37
MAIN1 ......................................................................................................................................................................37
MAIN2 ......................................................................................................................................................................38
RUN TIME POLYMORPHISM MAIN3 .................................................................................................................................38
Assignment: ...................................................................................................................................................................... 39

ABSTRACT CLASSES .............................................................................................................................................. 41

EXPLANATION: .............................................................................................................................................................41
EXAMPLE: ...................................................................................................................................................................41

INTERFACE ........................................................................................................................................................... 42

8
Your Success, Our Strength TM

EXPLANATION: .............................................................................................................................................................42
ABSTRACT CLASS VS. INTERFACE ......................................................................................................................................42
EXAMPLE1 ..................................................................................................................................................................42
EXAMPLE2 IMPLEMENTING MULTIPLE INTERFACES ..............................................................................................................43
EXAMPLE3 INHERITING INTERFACES .................................................................................................................................44

NON INHERITABLE CLASS ..................................................................................................................................... 45

EXAMPLE ....................................................................................................................................................................45

ENUMERATION .................................................................................................................................................... 45

OVERRIDING TOSTRING () FUNCTION .................................................................................................................. 46

EXAMPLE: ...................................................................................................................................................................46

UNDERSTANDING CONSOLE ................................................................................................................................ 47

CREATING NAMESPACE ....................................................................................................................................... 47

COMMAND LINE ARGUMENTS............................................................................................................................. 48

PASSING COMMAND LINE ARGUMENTS .............................................................................................................................48


Assignment ....................................................................................................................................................................... 49

USING VB6.0 FILE HANDLING IN VB.NET .............................................................................................................. 50

USING MICROSOFT.VISUALBASIC NAMESPACE ...................................................................................................................50

.NET FILE HANDLING ............................................................................................................................................ 51

USING SYSTEM.IO NAMESPACE .......................................................................................................................................51

SMALL-SMALL BIG-BIG FUNCTIONS ..................................................................................................................... 52

CREATING DIRECTORY....................................................................................................................................................52
COPY ONE FILE TO ANOTHER ...........................................................................................................................................52
GETTING DRIVE INFORMATION........................................................................................................................................52

UNDERSTANDING SYSTEM.ENVIRONMENT ......................................................................................................... 53

GETTING USER NAME ...................................................................................................................................................53


GETTING CURRENT DIRECTORY .......................................................................................................................................53
GETTING SYSTEM DIRECTORY .........................................................................................................................................53
GETTING FOLDER PATH .................................................................................................................................................53
GETTING OPERATING SYSTEM VERSION ............................................................................................................................53
CHECKING WHETHER IT IS 64 BIT OS OR NOT .....................................................................................................................53

UNDERSTANDING MY.COMPUTER ....................................................................................................................... 54

GETTING GMT TIME .....................................................................................................................................................54


CHECKING VARIOUS KEYS LIKE CAPS LOCK, NUM LOCK, SHIFT ETC… .........................................................................................54
CHECKING WHETHER MOUSE IS LEFT HANDED OR RIGHT HANDED ...........................................................................................54
GETTING COMPUTER NAME ............................................................................................................................................54
CHECKING TOTAL PHYSICAL MEMORY................................................................................................................................54
CHECKING TOTAL VIRTUAL MEMORY .................................................................................................................................54
CHECKING AVAILABLE PHYSICAL MEMORY ..........................................................................................................................54

9
Your Success, Our Strength TM

CHECKING SCREEN INFORMATION, RESOLUTION ETC… .........................................................................................................54


GETTING OS PLATFORM ................................................................................................................................................54
GETTING CULTURE ........................................................................................................................................................54
FILE SYSTEM ................................................................................................................................................................54
Assignment ....................................................................................................................................................................... 55

GENERATING RANDOM NUMBERS ...................................................................................................................... 56

USING SYSTEM.COLLECTIONS .............................................................................................................................. 56

STACK ........................................................................................................................................................................56
QUEUE .......................................................................................................................................................................57

USING SUBSTRING FUNCTION.............................................................................................................................. 58


Assignment ....................................................................................................................................................................... 58

DATETIME FUNCTIONS ........................................................................................................................................ 59


Assignment: ...................................................................................................................................................................... 59

EXCEPTION HANDLING ......................................................................................................................................... 60

TRY-CATCH .................................................................................................................................................................60
TRY – THROW – CATCH .................................................................................................................................................60
TRY – THROW – MULTIPLE CATCH ..................................................................................................................................61
EXCEPTION CLASS.........................................................................................................................................................62
USING EXCEPTION CLASS................................................................................................................................................62
TRY – THROW – CATCH – FINALLY ...................................................................................................................................63
NESTED TRY ................................................................................................................................................................64
NESTED – TRY EXAMPLE ................................................................................................................................................64
EXAMPLES OF VARIOUS EXCEPTIONS.................................................................................................................................65
USER – DEFINED EXCEPTION ..........................................................................................................................................65
USER – DEFINED EXCEPTION EXAMPLE .............................................................................................................................66
Assignment ....................................................................................................................................................................... 66

WINDOWS APPLICATIONS ................................................................................................................................... 67

A LOOK AT CONTROLS IN VB.NET ...................................................................................................................................67

CREATING FIRST WINDOWS APPLICATION ........................................................................................................... 68

SECOND WINDOWS APPLICATION ....................................................................................................................... 70

LIST OF CONTROLS; WE WILL BE LOOKING AT ...................................................................................................... 71

LABEL ................................................................................................................................................................... 73

PROPERTIES WINDOW: ..................................................................................................................................................73


EVENTS: .....................................................................................................................................................................73

TEXTBOX .............................................................................................................................................................. 74

PROPERTIES WINDOW: ..................................................................................................................................................74


EVENTS: .....................................................................................................................................................................74

FORM................................................................................................................................................................... 75

10
Your Success, Our Strength TM

PROPERTIES WINDOW: ..................................................................................................................................................75


EVENTS: .....................................................................................................................................................................75

BUTTON ............................................................................................................................................................... 76

PROPERTIES WINDOW: ..................................................................................................................................................76


EVENTS: .....................................................................................................................................................................76

A FUNNY APPLICATION – CONFUSION! ................................................................................................................ 77

AGAIN CONFUSION!! ........................................................................................................................................... 78

CHECKBOX ........................................................................................................................................................... 79

PROPERTIES WINDOW: ..................................................................................................................................................79


EVENTS: .....................................................................................................................................................................79
EXAMPLE: ...................................................................................................................................................................79

TRACKBAR ........................................................................................................................................................... 81

PROPERTIES WINDOW: .................................................................................................................................................81


EVENTS: .....................................................................................................................................................................81
EXAMPLE: ...................................................................................................................................................................81

VSROLLBAR .......................................................................................................................................................... 82

EXAMPLE: ...................................................................................................................................................................82
Assignment ....................................................................................................................................................................... 82

TIMER .................................................................................................................................................................. 83

PROPERTY WINDOW:....................................................................................................................................................83
EXAMPLE: ...................................................................................................................................................................83

LINKLABEL ............................................................................................................................................................ 84

EXAMPLE: ...................................................................................................................................................................84

PROGRESSBAR ..................................................................................................................................................... 85

EXAMPLE: ...................................................................................................................................................................85

WEBBROWSER ..................................................................................................................................................... 86

EXAMPLE: ...................................................................................................................................................................86

MASKEDTEXTBOX ................................................................................................................................................ 87

RADIOBUTTON .................................................................................................................................................... 88

EXAMPLE: ...................................................................................................................................................................88

A BIG CONFUSION!!! ............................................................................................................................................ 89

CONFUSION SOLVED ............................................................................................................................................ 90

COMBOBOX ......................................................................................................................................................... 91

EXAMPLE: ...................................................................................................................................................................91

STILL, CONFUSION!!! ............................................................................................................................................ 92

11
Your Success, Our Strength TM

CONFUSION SOLVED: ....................................................................................................................................................92

COLORDIALOG ..................................................................................................................................................... 93

EXAMPLE: ...................................................................................................................................................................93

FONTDIALOG ....................................................................................................................................................... 94

EXAMPLE: ...................................................................................................................................................................94

FOLDERBROWSERDIALOG .................................................................................................................................... 95

EXAMPLE: ...................................................................................................................................................................95

OPENFILEDIALOG ................................................................................................................................................. 96

EXAMPLE: ...................................................................................................................................................................96

ADOBEPDF ........................................................................................................................................................... 97

EXAMPLE: ...................................................................................................................................................................97

NUMERICUPDOWN .............................................................................................................................................. 98

EXAMPLE: ...................................................................................................................................................................98

MONTHCALENDAR............................................................................................................................................... 99

DATETIMEPICKER ................................................................................................................................................. 99

EXAMPLE: ...................................................................................................................................................................99

MESSAGEBOX .................................................................................................................................................... 100

VARIANTS OF MESSAGEBOX: ........................................................................................................................................100

INPUTBOX .......................................................................................................................................................... 100

VARIANTS OF INPUTBOX: .............................................................................................................................................100

LISTBOX ............................................................................................................................................................. 101

EXAMPLE: .................................................................................................................................................................101
CONFIGURE LISTBOX FOR MULTIPLE SELECTIONS ...............................................................................................................102

CHECKLISTBOX ................................................................................................................................................... 104

EXAMPLE: .................................................................................................................................................................104

MENUSTRIP ....................................................................................................................................................... 105

CONTEXTMENUSTRIP......................................................................................................................................... 107

ERRORPROVIDER: .............................................................................................................................................. 108

RICHTEXTBOX .................................................................................................................................................... 109


Assignment: .................................................................................................................................................................... 109

FLOWLAYOUT .................................................................................................................................................... 110

FLOWLAYOUT EXAMPLE: .............................................................................................................................................110

TABLELAYOUT .................................................................................................................................................... 110

12
Your Success, Our Strength TM

TABLELAYOUT EXAMPLE: .............................................................................................................................................110

MEDIAPLAYER.................................................................................................................................................... 111

TOOLTIP ............................................................................................................................................................. 113

PICTUREBOX ...................................................................................................................................................... 114

STATUSSTRIP ..................................................................................................................................................... 114

EXAMPLE: .................................................................................................................................................................115

TOOLSTRIP ......................................................................................................................................................... 116

ADDING STANDARD ITEMS: ..........................................................................................................................................117

TABCONTROL ..................................................................................................................................................... 118

SOME HINTS: ............................................................................................................................................................118

PRINTING: .......................................................................................................................................................... 118

PRINTDIALOG AND PRINTFORM ........................................................................................................................ 119

ADDING CONTROLS AT RUNTIME ...................................................................................................................... 119

ANIMATION: ...................................................................................................................................................... 120

NOTE: ......................................................................................................................................................................121

GRAPHICS: ......................................................................................................................................................... 122

DRAWING LINE AND RECTANGLE: ..................................................................................................................................122

NOTIFYICON....................................................................................................................................................... 122
Assignment: .................................................................................................................................................................... 124

DATABASE CONNECTIVITY ................................................................................................................................. 125

ADO.NET ................................................................................................................................................................125
BASIC STEPS TO FOLLOW:.............................................................................................................................................125
DISPLAYING ALL RECORDS AT A TIME USING DATA ADAPTER AND DATA SET ...........................................................................126
SEARCHING USING DATA ADAPTER AND DATA SET ............................................................................................................127
READING ONE VALUE AT A TIME USING DATA ADAPTER AND DATA SET .................................................................................128
READING ONE VALUE AT A TIME USING COMMAND AND DATA READER ..................................................................................129
SEARCHING USING COMMAND: .....................................................................................................................................130
SEARCHING USING COMMAND AGAIN: ............................................................................................................................131
INSERTION INTO TABLE USING COMMAND:......................................................................................................................132
DELETION USING COMMAND: .......................................................................................................................................132
UPDATE USING COMMAND: .........................................................................................................................................132

13
Your Success, Our Strength TM

.NET History

.NET History
 .NET 1.0 2002
 .NET 1.1 2003
 .NET 2.0 2005
 .NET 3.0 2007
 .NET 3.5 2008
 .NET 4.0 2010

.NET 2010 is the latest version of .NET. We will be using the same in our programs.

Applications that can be developed under .NET


 Console Applications
 Windows Applications
 Web Applications
 Component Libraries
 Windows Custom Control
 Web Custom Control
 Web Service
 Windows Service
 And lots more…

Visual Studio Integrated Developed Environment

Why to use VS IDE


 Drag and Drop Design
 IntelliSense features
 Syntax highlighting and auto syntax checking
 Excellent debugging tools
 Integrated with Visual Source Safe
 Easy Project Management
 When we install VS IDE, .NET Framework is
automatically installed.
 We will be using VS 2010 in our programs.

I will recommend going thru “Review VB6.0” before moving on.

14
Your Success, Our Strength TM

Types of Applications

Single tier Applications:


A single executable file handles all functions relating to user, business and data service layer.
Such an application also called monolithic application. Ex: Very early COBOL applications, console
applications (DOS mode applications), In Dbase and FoxPro; user interface is with Database.

Two tier Applications:


It divides application in two parts
- Client which implement user interface
- Server which stores data
these both may be located separately or on a single machine. Ex: VB + SQL Server

 Fat Client:
Business services layer combine with user services layer. Client executes presentation
logic and enforces business rules. Server stores data and process transactions. Fat client model is use
when server is overloaded with transaction processing activities and not available to process business
logic.

 Fat Server:
Business services layer combine with data services layer. As business services stored on
server most of processing take place on server.

 Dividing business services between user and data services:


Processing of business logic is distributed between user and data services.

15
Your Success, Our Strength TM

Limitations of two tier applications:


- Same Operating System required on both sides
- Executable file should be on client side
- Dedicated LAN requirements for both the tiers

Three tier Applications:


The services layer resides separately, either on same or on different machine. The user interface
interacts with business logic which validates data send by user interface and forwards to database if it
confirm to requirement. The front-end only interact with business logic which in turn interacts with
database.

n – Tier Applications:
An n tier architecture/ application use multiple server handling business services. This
architecture provides various advantages over other architectures. Ex: extensibility, maintainability and
scalability. One of most important requirements of such application is the ability to interchange info
across platform and to benefit from the functionality provided by other application. In other words,
there should be increased interoperability and integration between various applications. A website may
register its consumers and provides services to them; however it may not be capable of interacting with
other websites that providing complementary services to customers. For performing such tasks;
applications needs to provide cross platform application integration.

16
Your Success, Our Strength TM

Why to use .NET

Advantages of using .NET Framework


 Consistent Programming Model
 Rich Functionality (no need to go in low level details)
 Easy development of web application
 Object Oriented Programming (Object is mother of all)
 Multi Language Support
 Multi Device Support
 Automatic Memory Management (garbage collection)
 DLL hell removed
 XML support
 Ease of deployment and configuration
 Security

I left details of these points as an assignment to you.

.NET Architecture

17
Your Success, Our Strength TM

.NET framework exists as a layer between .NET applications and underlying Operating System. The
above figure shows components of .NET framework.

Layer 1:
Layer 1 Consists of web forms, windows forms and console applications that constitute to the
presentation layer of an application. Web forms are used in web applications where as windows forms
are used in windows based applications for providing interacting user interface. In addition, you can
create character based console application that can be executed from command line.

Layer 2:
One of the most important features of .NET Framework class library is that it can be used in a
consistent manner across multiple languages. This means, you can use same set of classes for
performing a specific task in VB.NET as well as in C++.NET. The .NET Framework class libraries contain
namespaces which are contained within assemblies.

Layer 3:
The common language runtime provides functionality such as exception handling, security,
debugging, and version control to any language that target it. This means that common language
runtime can host a variety of languages and offer a common set of tools across these languages ensuring
interoperability between codes. Ex: the runtime can execute programs written in any language such as
VB.NET, C#.NET and C++.NET with manage extension.

Manage Code
- Code that is developed with a language compiler that target CLR called manage code
- Code that is developed without considering the conventions and requirements of runtime
called unmanaged code. Unmanaged code runs in CLR with limited debugging and without
garbage collection process.

Garbage Collection Process


It manages allocation and de-allocation of memory for an application. Whenever you create an
object, the runtime allocates memory for object from manage heap. The manage heap is a region with
one or more pages of reserved address spaces that can be sub divided and allocated in smaller junks. If
runtime is unable to locate sufficient memory on manage heap; it invokes garbage collection process
which runs through all objects and terminates objects that are no longer used by an application.

18
Your Success, Our Strength TM

Namespaces:
Namespaces helps you to create logical groups of related classes and interfaces that can be used
by any language targeting .NET framework. Namespaces allow you to organize your classes so that they
can be easily accessed in other application. Namespaces can also be used to avoid any naming conflicts
between classes that have same name. Ex: you can use two classes with same name in an application
provided they belong to different namespaces. You can access classes belonging to a namespace by
simply using namespace name followed by dot (.) and then class name.
Ex: System.console => here System is namespace and console is class name

Assembly:
Assembly is a single deployable unit that contains all information about implementation of
classes, structure and interfaces. An assembly stores all information about itself and this information
called Meta data and includes the name and version number of assembly, security information and
information about dependencies, list of files that constitute assembly. All the application developed
using .NET framework made up of assembly. Namespaces are also stored in assemblies. Assemblies and
metadata provide the CLR with the information required for execution of an application. Assembly
provides this information to CLR while application is being executed. Assembly also plays an important
role in deployment and version control.

19
Your Success, Our Strength TM

Manage Code Execution Process

Explanation:
When you compile a program develop in a language that targets the CLR, instead of compiling
the source code into machine level code, the compiler translate it to Microsoft Intermediate Language
(MSIL) or Intermediate Language (IL). No matter which language has been used to develop the
application, it always gets translated into IL; this ensures language interoperability. Compiler also
produces Meta data about the program/ application during process of compilation. Meta data contains
description of program such as classes and interfaces, version of components stored in program. IL and
metadata linked in an assembly.

When you execute .exe/ .dll file, the IL and other information from base class library is sent to
class loader. Class loader loads code in memory.

Before code can be executed, .NET framework needs to convert the intermediate language into
native or CPU specific code. JIT compiler translates the code from IL to managed native code. During

20
Your Success, Our Strength TM

process of compilation, JIT compiles only code that is required. During execution, instead of compiling
complete code, when an un-compiled method is invoked during execution, JIT compiler converts IL for
that method into native code. This process saves the time and memory required to convert complete IL
into native code.

During JIT compilation, code is also check for Type Safety. Type Safety ensures that objects are
always accessed in a compatible way.

While executing code, a security check is performed to ensure that code has appropriate
permission for accessing available resources.

First VB.NET Program

Hello World again!!!


 Open Visual Studio 2010 and click on New Project; a dialog box will open, choose language VB and
from application choose Console Application.

 Some key points


o VB.NET is case – Insensitive language
o Console.Writeline is used to print a line on console followed by new line
o Console.Write is used to print a line
o Console.Read is used to read a character followed by Enter
o Console.ReadKey is used to read a key
o Console.ReadLine is used to read a line followed by Enter
o Variable Declaration Review:
 Dim <variable name> as <data type>

21
Your Success, Our Strength TM

Some built in data types:

 Boolean
 Byte
 Char
 DateTime
 Decimal
 Double
 Int16
 Int32
 Int64
 SByte
 Single
 TimeSpan
 Write the following code in your Console Application code window

 To execute your program, press ctrl + F5

22
Your Success, Our Strength TM

Second VB.NET program

Key Points:

 We can use System.Console.Write


System namespace is included in our programs, so it is optional to write System
 Convert.int32 is used to convert string to integer type
 Every read line is string by default, we have to convert it to specific type, we want to use.

23
Your Success, Our Strength TM

Third program (using structures)

Key Points:

 Type of VB is replaced by Structure in VB.NET


 In VB, we can change base of arrays by using option base 1, in VB.NET; all arrays are 0 based
 Variant data type is not supported in .NET
 Currency data type is replaced by decimal
 VB.NET supports shortcuts operators like I += 1
 Dim a, b as integer => in VB.NET a and b both are integers
 VB.NET also supports block scope
 Return value of function is supported by return statement
 Empty and Null is replaced by Nothing in vb.NET
 Wend is replaced by End While in VB.NET
 Boxing : changing value type to reference type
 Unboxing : changing reference to value type

24
Your Success, Our Strength TM

Using if-else

Using conditional operator

Key Points:

 Option Explicit ON => it will force you to declare each variable before it is being used
 Option Explicit OFF
 Option Strict ON => to stop automatic conversion like from int to long
 Option Strict OFF
 ByVal => to pass a parameter by value
 ByRef => to pass a parameter by reference
 We can comment a line by pressing ‘ in beginning of a line.
 Boolean Operators:
o AND
o OR
o NOT
o XOR
o ANDALSO
o ORELSE

I left `using Boolean operators’ as an assignment for you.

25
Your Success, Our Strength TM

Looping

Assignment:
1. Print table of a number using for loop, do-while loop, do-until loop
2. Read a number from console and check whether it is prime or not
3. Ask two numbers from user and check which number is greater using conditional operator

26
Your Success, Our Strength TM

Defining arrays & for-each loop

Subroutine vs. Function


Subroutine cannot return a value while functions can return a value
Subroutine starts with sub keyword and functions start with function keyword
both names are followed by name then parameter list and functions are then followed by return type
Subroutines are ended by end sub while functions are ended by end function
While calling subroutine or functions, parenthesis are necessary
Calling method is same for both subroutine and functions
fun_name ()
sub_name ()
By default arguments are passed by value, we can pass the arguments by using by reference by using
byref keyword instead of byval
We can make parameters default/optional by writing optional keyword before byval or byref keywords
and specifying their values after variable declaration as
Optional byval j as integer = 10

27
Your Success, Our Strength TM

Definition of subroutine and function

Multi dimension arrays

To shrink and grow array size, we use redim

but redim will delete all the data stored in array, to preserve that we use preserve keyword

Retrieving lower and upper bound

Assignment
1. Addition of 2 matrix of order 2X2
2. Initially stores names of 5 students, then change array to hold 10 names and print 10 names
using for-each loop
3. Define a function factorial which returns factorial of a number
4. Make a subroutine which swaps two integers
5. Make a subroutine which swaps two integers without using third variable
6. Print following
1
12
123
1234

28
Your Success, Our Strength TM

Using Select-Case

Function overloading

29
Your Success, Our Strength TM

Assignment
1. Overload area() function to calculate area of circle and rectangle.
2. Overload sum() function to sum 2 integers, 2 doubles and 2 strings
3. Overload volume() function to calculate volume of cube, cylinder and cuboid

Defining Classes

Making a simple class

30
Your Success, Our Strength TM

Creating constructor

31
Your Success, Our Strength TM

Overloading constructor

32
Your Success, Our Strength TM

Defining Properties

Key Points:

 Properties can be readonly or writeonly also


 Write readonly or writeonly keyword before property keyword while defining properties.

33
Your Success, Our Strength TM

Operator Overloading

Assignment
1. Overload +,-,*,/ in complex class
a. You can use simple multiplication and division
2. Overload + and – in matrix class of order 3 X 3

34
Your Success, Our Strength TM

Inheritance

Code reusability
Time saving, cost saving

Types of inheritance
Single Level Inheritance
Multi level inheritance
Hierarchical Inheritance

Variable Scope
Private => accessible in member functions only
Protected => accessible in derived class also
Public => accessible outside the class also

How to inherit

35
Your Success, Our Strength TM

Inheritance Example

36
Your Success, Our Strength TM

Run Time Polymorphism

Object slicing, Run Time Binding, Late Binding


Early bounding includes Operator overloading and function overloading which we had already covered.
In case of runtime polymorphism, which function to be called; will be decided at run-time.

Example

Main1

37
Your Success, Our Strength TM

Main2

Run Time Polymorphism


Main3

38
Your Success, Our Strength TM

Assignment:
1. Assume that a bank maintains two kinds of accounts for customers, one called as saving account
and other as current account. The savings account provides compound interest and withdrawal
facilities but no cheque book facility. The current account provides cheque book facility but no
interest. Current account holders should also maintain a minimum balance and if the balance
falls below this level, a service charge is imposed.
Create a class account that stores customer name, account number and type of account. From
this derive the classes’ cur_acct and sav_acct to make them more specific to their requirements.
Include necessary member functions in order to achieve the following tasks:
a. Accept deposit from a customer and update the balance.
b. Display the balance
c. Compute and deposit interest
d. Permit withdrawal and update the balance
e. Check for the minimum balance, impose penalty, necessary, and update the balance

Don’t use any constructors. Use member functions to initialize the class members.

2. Specify all the classes as shown in figure and define functions to create the database and retrieve
individual information as and when required

39
Your Success, Our Strength TM

3. Create a base class called shape. Use this class to shore two double type values that could be
used to computer the area of figures. Derive two specific classes called triangle and rectangle
from the base shape. Add to the base class, a member function get_data() to initialize base class
data members and another member function display_area() to computer and display the area of
figures. Override display_area() in derive classes to suit their requireents.
Using these three classes, design a program that will accept dimensions of a triangle or a
rectangle interactively, and display the area.
Remember two values given as input will be treated as lengths of two sides in case of rectangles
and as base and height in case of triangles, and used as follows:
Area of rectangle = x * y
Area of triangle = ½*x*y

4. Extend the above program to display area of circles. This requires addition of a new derived class
circle that computes the area of a circle. Remember, for a circle we need only one value, its
radius, but the get_data() function in the base class requires two values to be passed. (Hint:
Make the second argument of get_data() function as a default/ optional one with zero value)

40
Your Success, Our Strength TM

Abstract Classes

Explanation:
Abstract classes are used to create template for other classes.
We can’t create object of abstract classes.
In VB.NET abstract classes are declared by the keyword “mustinherit”
As we can’t create object of abstract class, so there is no use of defining any function, so we declare
functions/ subroutine with the keyword “mustoverride”

Example:

41
Your Success, Our Strength TM

Interface

Explanation:
~ An alternative to abstract classes
~ less formality as compared to abstract classes

Abstract Class vs. Interface


One abstract class can be inherited Multiple interfaces can be implemented
Abstract classes are inherited in derive classes Interfaces are implemented
Members in abstract class can / can’t have Members in interfaces can’t have definition
definition
Derive class define functions of abstract class but Class implementing interfaces must override /
not necessary to override all functions implement all functions declared in interface

Example1

42
Your Success, Our Strength TM

Example2
Implementing multiple interfaces

43
Your Success, Our Strength TM

Example3
Inheriting interfaces

44
Your Success, Our Strength TM

Non Inheritable Class


As the name is stating, this class can’t be inheritable further.

Example

Enumeration

Key points:

1. Default value is 0 for first name in enumeration


2. Rest all will get incremented value.

45
Your Success, Our Strength TM

Overriding tostring () function


It’s like overloading output operator.

Example:

46
Your Success, Our Strength TM

Understanding console

Creating Namespace

47
Your Success, Our Strength TM

Command Line Arguments

Passing command line arguments


You can pass arguments from command prompt like exefilename firstarg secondarg …
For testing purpose you can pass arguments from VSIDE also.

1. Go to project menu and choose <your application> properties. For me, its’ consoleapplication1
properties
2. Choose debug tab from left pane and in command line textbox, write your arguments

3. Now execute your project

48
Your Success, Our Strength TM

Assignment
1. Make a vehicle class, overload properties for registration number and model number. Also
override tostring () function in vehicle class
2. Use command line arguments to perform +, - , *, /. For example, user will provide first number
then operator and then second number like
a. Consoleapplication1.exe 10 + 20
3. Define a test class in a namespace sample. Define input and output function for the class test
and use them in main.
4. Make an enumeration month. User will enter a numeric month, use select case to check the
month name and print number of days for the same.

49
Your Success, Our Strength TM

Using VB6.0 File Handling in VB.NET

Using Microsoft.VisualBasic namespace

50
Your Success, Our Strength TM

.NET File Handling

Using System.IO namespace

51
Your Success, Our Strength TM

Small-Small Big-Big Functions

Creating directory

Copy one file to another

Getting Drive information

52
Your Success, Our Strength TM

Understanding System.Environment

Getting User Name

Getting Current Directory

Getting System Directory

Getting Folder Path

Getting Operating System Version

Checking whether it is 64 bit OS or not

53
Your Success, Our Strength TM

Understanding My.Computer

Getting GMT time

Checking various keys like caps lock, num lock, shift etc…

Checking whether mouse is left handed or right handed

Getting computer name

Checking total physical memory

Checking total virtual memory

Checking available physical memory

Checking screen information, resolution etc…

Getting OS platform

Getting culture

File System

54
Your Success, Our Strength TM

Assignment
Try out various function of My.Computer.FileSystem at your own.

55
Your Success, Our Strength TM

Generating Random numbers

Using System.Collections

Stack

56
Your Success, Our Strength TM

Queue

57
Your Success, Our Strength TM

Using Substring function

Assignment
There are lot many functions of strings. Try them at your own.

58
Your Success, Our Strength TM

DateTime functions

Assignment:
1. Write a program to copy one file to another
2. Write a program which read from 2 files and write into third file
3. Write a program which read form one file and copy all even lines to second file and odd lines
to third file
4. Write a program which read input lines from users and save them in a file on desktop and
then read those lines from file and display it to user
Hint: use getfolderpath() to get path of desktop
5. Write a program for parsing using stack
6. Write a program which converts infix to postfix and evaluate the postfix expression
7. Write a program which converts infix to prefix and evaluate the prefix expression

59
Your Success, Our Strength TM

Exception Handling
I am not covering theory part as every book has long stories on what are exceptions. Here we are
directly going to look at procedure to handle exceptions.

1. Find the problem


2. Inform that an error has occurred
3. Receive the error information
4. Take corrective action

Try-Catch

Try – Throw – Catch

60
Your Success, Our Strength TM

Try – Throw – Multiple Catch

61
Your Success, Our Strength TM

Exception Class
- It’s base class of all other exception classes
- Used basically to handle those exception which programmer either forget to handle
or programmer was not able to classify
- Also used to define user defined exceptions

Using Exception class

62
Your Success, Our Strength TM

Try – Throw – Catch – Finally

63
Your Success, Our Strength TM

Nested Try
In case inner try was not able to handle the exception, it will search catch in outer try.

Nested – Try Example

64
Your Success, Our Strength TM

Examples of various Exceptions


Try various exceptions at your own.

User – Defined Exception


- It must be inherited from Exception class
- You have to override tostring() function
- You have to override message property

65
Your Success, Our Strength TM

User – Defined Exception Example

Assignment
Try some examples on exceptions at your own

66
Your Success, Our Strength TM

Windows Applications
I expect you are comfortable with Microsoft Visual Basic 6.0. Incase you don’t have knowledge about
Visual Basic 6.0, I will suggest you to first go thru with that.

Here, we will be referring directly to the some common properties and some common events of
controls.

A look at controls in VB.NET

67
Your Success, Our Strength TM

Creating First Windows Application


1. Choose new project
2. From the open dialog box, choose windows application and click okay
3. Form will appear in Design mode

Remember:

In .NET, each control is having text property instead of text and caption property and the most
important line, everything is based on namespaces, classes and object is mother of all.

68
Your Success, Our Strength TM

4. Drag the label and double click the form


5. On form_load event write

Remember:

Me refers to current form. In VB.NET, you can’t use current form name in current form class, so
we will be use Me if we want to refer to current class.

6. To execute the application, press ctrl + F5 or simply press play button in toolbar

69
Your Success, Our Strength TM

Second Windows Application

Design a Form like

Change text properties from properties menu. I am here not changing name properties of controls; you
can change them as per your convenient.

And write button1_click event

70
Your Success, Our Strength TM

List of Controls; we will be looking at

1. Form
2. Button
3. CheckBox
4. CheckListBox
5. ColorDialog
6. Combo
7. ContextMenu
8. DataGrid (at a later stage)
9. DateTimePicker
10. DomainUpDown
11. ErrorProvider
12. FontDialog
13. GroupBox
14. HScrollBar
15. Label
16. LinkLabel
17. ListBox
18. ListView
19. MaskedTextBox
20. MenuStrip
21. MonthCalendar
22. NotifyIcon
23. NumericUpDown
24. OpenFileDialog
25. Pannel
26. PictureBox
27. ProgressBar
28. RadioButton
29. RichTextBox
30. SaveFileDialog
31. StatusStrip
32. TabControl
33. TextBox
34. Timer
35. ToolTip
36. ToolStrip
37. TrackBar
38. VScrollBar

71
Your Success, Our Strength TM

39. MediaPlayer
40. WebBrowser
41. AdobePdf
42. TableLayout
43. FlowLayout
44. FolderBrowserDialog
45. PrintDialog
46. PrintForm
47. Animation Control
48. Drawing Graphics
49. MessageBox
50. InputBox

These controls are described in an order to make the reader comfortable and to make learning more
interesting.

72
Your Success, Our Strength TM

Label

Properties window:
1. AutoSize : True ( Label will automatically adjust its size )
2. BackColor : to change its background color
3. BorderStyle : single or 3D
4. ContextMenuStrip : To change right click menu; we will look in detail about this option
5. Cursor : you can change mouse cursor which should appear on this label
6. Dock : Where and how this label should appear
7. FlatStyle : Looks of label
8. Font
9. ForeColor : text color of label
10. Image: Image which will appear on label
11. ImageAlign : Left / Right / Center
12. RightToLeft : If yes, text will appear from right to left
13. Text : text to be appear on label

Events:

All the event arguments are available to us with the object “e”.

73
Your Success, Our Strength TM

TextBox

Properties window:
Same as of label control, some new properties are shown here

1. Multiline = true ( you can write multiple lines in textbox; by default, textbox is single line)
2. Password char = * ( now the text appearing in textbox will be marked as * ; you can use any
character)
3. ReadOnly = True ( now user can read the text of textbox, he can’t modify it)
4. ScrollBar = None / Horizontal / Vertical / Both
5. WordWrap = True
6. TabStop = True ( Using Tab key, you can focus on this control )
7. TabIndex, to set tab preference, when tab should appear on it.

I will recommend you to try all properties of properties window.

Events:

74
Your Success, Our Strength TM

Form

Properties window:
1. BackgroundImage
2. BackgroundImageLayout
3. ControlBox = False ( minimize, maximize and close button will not appear)
4. FormBorderStyle ( Try all these options and see effects)
5. MaximizeBox = False (Maximize button will get disable on form)
6. MinimizeBox
7. Opacity (to set transparency of Form, Try using with 80% and 50%, Default is 100%)
8. ShowInTaskbar = False (When you execute your form, your form will not appear in Taskbar)
9. Text = to change title bar text of form
10. TransparencyKey = white ( which color of form you want to be transparent, if I have selected
white, then the white color, wherever on form , will be transparent)

Events:

75
Your Success, Our Strength TM

Button

Properties window:
Properties are similar to textbox and label, try them at your own.

Events:

76
Your Success, Our Strength TM

A Funny Application – Confusion!


1. Design your form like

2. Program it as

3. Now execute it

77
Your Success, Our Strength TM

Again Confusion!!
1. Design same form again

2. Program it as

3. Now execute your program and try to type!!!

78
Your Success, Our Strength TM

CheckBox

Properties window:
1. Checked: (Initially, when form is loaded, this checkbox will be checked or not)
2. ThreeState : True ( Then checkbox can have three states : Unchecked, Checked or intermediate )

Events:

Example:
Design your form as:

Program it as:

79
Your Success, Our Strength TM

Result:

80
Your Success, Our Strength TM

TrackBar

Properties Window:
1. Minimum and Maximum value
2. RightToLeft
3. Orientation : Horizontal or Vertical

Events:

Example:

81
Your Success, Our Strength TM

VSrollBar

Example:

Assignment
Try HScrollBar at your own.

82
Your Success, Our Strength TM

Timer
Simply drag the timer on your form. When you will drag, it will appear on the bottom bar IDE.

Property Window:
1. Enable: True ( to enable the timer, by default; its false)
2. Interval : duration after which timer will tick (1000 means 1 sec)

Example:

83
Your Success, Our Strength TM

LinkLabel
It will appear as a link on form. You can do the normal working on its click event or you can browse
some website as it looks states.

Example:

84
Your Success, Our Strength TM

ProgressBar

Example:
Simply drag a progressbar on your form. Change its minimum, maximum and style properties (if you
want)

Place a timer on your form. Change its interval to 1000 and enable to true

And program your timer as below and execute your program.

85
Your Success, Our Strength TM

WebBrowser

Example:
Drag WebBrowser on your form. By Default it is docked in form. Click on Top Right Arrow appearing on
WebBrowser Control and choose undock

Design your form as shown below

Initially, we are designing it with buttons, later you can create toolbar or menu bar and also you can use
images to change its Design.

86
Your Success, Our Strength TM

And now program it as:

I have changed name of controls to make programming more understandable.

That’s all we have to do and Thanks to Microsoft and our WebBrowser is ready!!!

MaskedTextBox
Use to specify a Mask/ Format.

Change its mask property and try it at your own. It’s similar to TextBox except its mask property.

Try this at your own.

87
Your Success, Our Strength TM

RadioButton

Example:
Design your form as:

And program it as:

And now execute your form:

88
Your Success, Our Strength TM

A Big Confusion!!!
Design your form as:

And program it as:

And now execute your form and try to select one option from both groups!!!

89
Your Success, Our Strength TM

Confusion Solved
Drag GroupBox from toolbox and design your form as:

And execute your form:

Now you can select one from each group.

90
Your Success, Our Strength TM

ComboBox

Example:
Design your form as:

and program it as:

And execute it, choose one day from combo box and click submit.

91
Your Success, Our Strength TM

Still, Confusion!!!
In above program, check carefully, user is able to change the text of ComboBox. User can edit the text of
combo box.

Confusion Solved:
Select the combo box and from properties menu, change its DropDownStyle to DropDownList.

And now execute your form.

Try DomainUpDown at your own. Its functionality is similar to ComboBox.

92
Your Success, Our Strength TM

ColorDialog

Example:
Simply drag color dialog on your form and program your form as:

And execute your form and click on form and change color…

93
Your Success, Our Strength TM

FontDialog

Example:
Drag font dialog on your form and design your form with a button and textbox and program it as:

And execute your form and test it…

94
Your Success, Our Strength TM

FolderBrowserDialog

Example:
Drag FolderBrowserDialog and a button on form and program it as:

And execute your form and choose a folder and click ok…

Using FolderBrowserDialog, you can ask user to select folder, where he wants to save files, and you can
get the path using FolderBrowserDialog.

Note: before showing this dialog, write


FolderBrowserDialog1.ShowNewFolderButton = False
and see what’s difference.

95
Your Success, Our Strength TM

OpenFileDialog

Example:
Drag OpenFileDialog and a button on form and program it as:

And execute your application…

Now you know the file handling; so instead of displaying filename in msgbox, you can read its contents
and show in textbox or you can perform some operations. Basic idea is to show you how to use
OpenFileDialog.

Note: Try SaveFileDialog at your own.

96
Your Success, Our Strength TM

AdobePdf

Example:
Drag AdobePdf, OpenFileDialog and a button on your form and program it as:

And now execute your form:

97
Your Success, Our Strength TM

NumericUpDown

Example:
Drag NumericUpDown and a button on form. You can change minimum and maximum value of
NumericUpDown from properties menu. Program your button as:

And execute your form:

98
Your Success, Our Strength TM

MonthCalendar
Try this at your own. Try out all its properties. It’s generally used to display calendar on form.

DateTimePicker
Using this control, you can get the value (Date) which user has selected.

Example:
Design your form as:

And execute your form:

99
Your Success, Our Strength TM

MessageBox
Till now, we are using Msgbox (), but this is a function of VB. Now we will be discussing MessageBox.

Variants of MessageBox:

InputBox
It’s used to take a value from user. It will return a string; you have to convert it to specific type before
using.

Variants of InputBox:

100
Your Success, Our Strength TM

ListBox

Example:
Simply drag a ListBox and a button on your form and program it as:

101
Your Success, Our Strength TM

Configure ListBox for multiple selections


Select ListBox on form and from its properties menu, change its SelectionMode to MultiSimple.

And now we have to retrieve all selected items, so we will program button_click as:

102
Your Success, Our Strength TM

And now execute your form:

ListView is similar to ListBox, Try ListView at your own.

103
Your Success, Our Strength TM

CheckListBox

Example:
Drag a CheckListBox and a button on form and program it as:

And now execute your form:

104
Your Success, Our Strength TM

MenuStrip
Drag the MenuStrip on form. You can directly edit the menus you want to create.

Use – if you want to create separator between menus. And you can assign ALT keys as shortcut by
writing & before that character.

105
Your Success, Our Strength TM

You can assign the shortcut keys by choosing that particular item and choose shortcut key from its
properties menu. For example: here I want to assign ctrl + s for my save menu

To program it, simply double click that menu item, which you want to program.

106
Your Success, Our Strength TM

ContextMenuStrip
It’s is similar to MenuStrip except that it doesn’t appear as normal menu bar, you have to assign
ContextMenu to some control, where user will right click to see the menu. Here, I am assigning
ContextMenu to TextBox as:

And now execute your form and right click on textbox.

107
Your Success, Our Strength TM

ErrorProvider:
Drag a textbox, a button and an error provider on form. Suppose we want to show an error message to
user, if textbox. Text is blank. We will write as:

And now execute your form:

108
Your Success, Our Strength TM

RichTextBox
Have you noticed the difference between notepad and WordPad? In WordPad, you can paste pictures;
you can change background and foreground color of selected text, however in notepad, all this is not
possible. So, the alternate to TextBox is RichTextBox.

Drag it to your form. By default it is multiline. Let’s look at some of its properties:

Assignment:
Make a Notepad Application using TextBox.
Enhance your notepad using RichTextBox.

109
Your Success, Our Strength TM

FlowLayout
Used to draw controls. Like a Panel or GroupBox. Draw a FlowLayout on your form and place your
controls inside it. Controls will appear automatically in flowing locations. Try this at your own.

FlowLayout Example:

TableLayout
You will find using FlowLayout is quite difficult because we can’t place controls at desired locations. One
alternative is TableLayout. You can place your controls in cells; you can insert some rows and columns
and can insert controls in cells. Try this control at your own.

TableLayout Example:

110
Your Success, Our Strength TM

MediaPlayer
Drag MediaPlayer, 3 buttons and an OpenFileDialog on your form and design your form as:

And program them as:

Execute your form and open a media file.

111
Your Success, Our Strength TM

Media Player has lots of properties. Try out all those properties.

112
Your Success, Our Strength TM

ToolTip
Drag a ToolTip and a button on form. Suppose we want to show ToolTip on this button. Select button
and from its properties window, choose ToolTip on ToolTip1 and set it to any value.

And now select ToolTip control which you have dragged on form and from its properties menu, you can
set its icon, isBalloon and ToolTipTitle.

113
Your Success, Our Strength TM

And now execute your form and move your mouse over Button.

PictureBox
Drag a PictureBox on your form and click on arrow appearing on top right corner; change SizeMode
property to different options and check their effects. You can change image of PictureBox in two ways as
shown below. Use any one method at a time.

StatusStrip
Drag a StatusStrip on Form; it will appear at the bottom of Form. You can add label, ProgressBar and
Dropdown by clicking on the “add new” icon appearing on StatusStrip.

114
Your Success, Our Strength TM

And now you can program them as you want.

Example:
Here, on status label, I want to show the number of characters in RichTextBox.

And now execute your form, type something in RichTextBox and check status label.

115
Your Success, Our Strength TM

ToolStrip
To create Toolbar. Drag ToolStrip on Form. By Default, it will appear on top corner. You can change its
back color, background image etc… (Check its properties window). Here, I am setting back color to
transparent.

There is also an “add new” button appearing on ToolStrip, you can add new items by clicking on it.
Suppose we are adding a Button, by default it will appear as image, right click on image button and
change its display style like image and text. Now you can change its image by choosing set image option
from context menu and its text can be changed from properties menu. Here I have added two buttons:

You can program them by simply double clicking on them. In ToolStrip you can Buttons, Dropdown,
Label, Separators, Progress Bar, and TextBox.

116
Your Success, Our Strength TM

Adding Standard items:


Simply select the toolbar. A small arrow will appear on top of toolbar. Click on that and you can add
standard items in your toolbar.

117
Your Success, Our Strength TM

TabControl
Drag a TabControl on your form. By default, only two tabs will be shown, you can add or remove tabs by
choosing TabPages from its properties menu. You can add your controls in it and program them. Now I
leave it to you, how creative you are!

Here are some properties which will help you:

Some Hints:
You can create MultiTab WebBrowser or you can create your notepad and tabbed menu to it.

Printing:
The simplest way, I found is- generate HTML report or open your document thru WebBrowser and user
will automatically do the page setup, print preview and print automatically…We don’t have to do all that
stuff.

118
Your Success, Our Strength TM

PrintDialog and PrintForm


Drag both PrintDialog and PrintForm on your form and program them as:

Adding Controls at runtime


1. Create an object of control type.
2. Adjust its various properties
3. Set its visibility
4. Bring it to front
5. Set its parent container
6. And finally show it.

119
Your Success, Our Strength TM

Animation:
We don’t have animation control present in our toolbox; we have to add it explicitly. Right click the
toolbox and click choose items and from the dialog box, choose com components and from that choose
Microsoft Animation Control, and click ok.

It will add animation control to your Toolbox; now drag Animation Control to your form.

120
Your Success, Our Strength TM

Animation Control can play .avi files, search for .avi files available on your PC. Generally, you have seen,
while copying files, animation plays on form. We will do something similar. Program your button as:

And now execute your form:

Try out other properties like stop etc…

Note:
Bundle of images and animation comes with VisualStudio2010. You can found them in similar path of
the path shown below:

“C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary\1033\”

Extract files and use them.

121
Your Success, Our Strength TM

Graphics:
Here, we have created a line and a rectangle; there are many functions available for graphics, Again I
leave it on you, how creative you are!

Drawing Line and Rectangle:

NotifyIcon
It appears in System Tray.

Drag NotifyIcon control to your form, select it and change its properties (icon, text and title).

122
Your Success, Our Strength TM

Note: Don’t forget to set its icon property from property menu.

And now on button_click write

And execute your form and click button:

123
Your Success, Our Strength TM

Assignment:
1. Design a Code Module for C++ or Java, like you have Visual Studio for .NET, Similar to this, Design
for C++ or Java, so that user don’t have to write so much, Everything Drag and Drop and in
background, code will appear automatically and user can view, edit or save it.

124
Your Success, Our Strength TM

Database Connectivity

ADO.NET
Here, I have tried to simplify the Database connectivity. The following figure explains how to connect
with database. We are showing here the connectivity with MS-Access, so that you can practice at home.
In the similar way, you can connect to SQL Server. MS-Access is not generally used because it can handle
only 35 clients at a time while SQL Server and Oracle can handle a large number of clients.

Basic Steps to follow:


1. Create a connection object
2. Set its value like connection string etc…
3. Open the connection
4. Do your work
5. Close the connection

125
Your Success, Our Strength TM

Displaying all records at a time using Data Adapter and Data Set
1. Open connection
2. Use Data Adapter to read from connection
3. Use Data Set to store data
4. And then display data from Data Set

Open windows application and drag DataGrid on it and program your form as:

And execute your form:

126
Your Success, Our Strength TM

Searching using Data Adapter and Data Set

127
Your Success, Our Strength TM

Reading one value at a time using Data Adapter and Data Set
Design a form with just a Label on it and program it as:

And execute your form:

128
Your Success, Our Strength TM

Reading one value at a time using command and data reader


Design a form with just a Label on it and program it as:

And execute form:

129
Your Success, Our Strength TM

Searching using command:


Design a form with just a Label on it and program it as:

130
Your Success, Our Strength TM

Searching using command again:


Design a form with just a Label on it and program it as:

131
Your Success, Our Strength TM

Insertion into Table using Command:

Deletion using Command:

Update using Command:

Now, I leave up to you, how you will use these commands in your project.

Further, You can also add Exception handling in this.

132
Your Success, Our Strength TM

The (copy left) extension:

- You can use the content presented in this for your


personal and professional purposes without any
permissions.
- All the material presented here is free of cost and
hence can’t be charged except distribution charges.

©MillenniumYear
Serial: 29062010172738

133