Notes
Notes
NET Framework
.NET is a software framework which is designed and developed by Microsoft. The first version
of .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine
for compiling and executing programs written in different languages like C#, VB.Net etc.
It is used to develop Form-based applications, Web-based applications, and Web services.
There is a variety of programming languages available on the .Net platform, VB.Net
and C# being the most common ones are . It is used to build applications for Windows, phone,
web etc. It provides a lot of functionalities and also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11 programming
languages are designed and developed by Microsoft. The remaining Non-Microsoft
Languages which are supported by .NET Framework but not designed and developed by
Microsoft.
11 Programming Languages which are designed and developed by Microsoft are:
• C#.NET
• VB.NET
• C++.NET
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML(Abstract State Machine Language)
Main Components of .NET Framework
1
Common Language Runtime(CLR): CLR is the basic and Virtual Machine component of
the .NET Framework. It is the run-time environment in the .NET Framework that runs the
codes and helps in making the development process easier by providing the various services
such as remoting, thread management, type-safety, memory management, robustness etc..
Basically, it is responsible for managing the execution of .NET programs regardless of any
.NET programming language. It also helps in the management of code, as code that targets the
runtime is known as the Managed Code and code doesn’t target to runtime is known as
Unmanaged code.
Framework Class Library(FCL): It is the collection of reusable, object-oriented class
libraries and methods etc that can be integrated with CLR. Also called the Assemblies. It is just
like the header files in C/C++ and packages in the java. Installing .NET framework basically
is the installation of CLR and FCL into the system. Below is the overview of .NET Framework
2
■ It is the collection of reusable, object-oriented class libraries and methods, etc that can
be integrated with CLR. Also called the Assemblies.
■ It is just like the header files in C/C++ and packages in the java.
■ Installing .NET framework basically is the installation of CLR and FCL into the
system.
■ Below is the overview of .NET Framework
■ The combination of Operating System Architecture and CPU Architecture is known as
the platform.
■ Platform dependent means the programming language code will run only on particular
Operating System.
■ A .NET application is platform dependent because of the .NET framework which is
only able to run on the Windows-based operating system.
■ The .Net application is platform independent also because of Mono framework.
■ Using Mono framework the .Net application can run on any Operating System
including windows.
■ Mono framework is a third party software developed by Novell Company which is
now a part of Micro Focus Company. It is a paid framework.
GC is a low priority thread that runs in the background of the .Net application. It helps in
destroying the objects from the memory that are no longer in used.
■ GC is automatic memory reclamation.
■ It is low-priority thread that always runs in the background of the application.
■ When memory is scarce, the priority of the garbage collector is elevated until sufficient
resources are reclaimed.
■ It is not certain when an object will be garbage collected.
A just-in-time (JIT) compiler
This additionally given, as it can convert the bytecode to the instruction, which can be feed
straight to your processor. It starts running just once your program starts and compiles your
source code on the fly (hence termed as just-in-time). It is typically faster than usual compiling.
It can access the runtime information dynamically, which is not possible by the normal
compiler.
3
CLS
■ CLS stands for Common Language Specification and it is a subset of CTS.
■ It defines a set of rules and restrictions that every language must follow which runs
under the .NET framework.
■ The languages which follow these set of rules are said to be CLS Compliant.
■ In simple words, CLS enables cross-language integration or Interoperability.
CTS
■ Common Type System (CTS) is a standard that specifies how Type definitions and
specific values of Types are represented in computer memory.
■ It is intended to allow programs written in different programming languages to easily
share information.
4
.NET Version CLR Version Development tool Windows Support
5
After clicking on particular symbol by mouse the instruction is given to computer so due to
that a person who doesn’t know English language can use the computer easily.
This graphics makes the communication between user and computer easy.
So in the system where communication is done with the help of graphics is called as Graphical
User Interface.
And vice versa is called as Command line User Interface.
Topic CUI GUI
Ease Because of the memorization and Although new users may have a
familiarity needed to operate difficult at time learning to use the
commanding interface new users find mouse to operate and use a GUI
it much more difficult to successfully most user pick up this interface
navigate and operate a command line much easier when compared to a
interface command line interface.
Control Users have much more control of Although GUI offers plenty of
their file system and operating controls of a file system and
system in a command line interface. operating system often advance
For example user can easily copy a users or users who need to do
specific file from one location to specific tasks may need to resort
another with one line command. to a command line to complete
that task.
Multitasking Although many command line GUI users have windows that
environments are capable of enable a user to easily view
multitasking they do not offer the control and manipulate multiple
same ease and ability to view things at once and are commonly
multiple things at once on one screen much faster to do when compared
to command line.
Speed Because command line users only A GUI may be easier to use
need to use their keyboards to because of the mouse. However
navigate a command line interface using mouse and keyboard to
and often only need to execute a few navigate and control your
lines to perform a task an advanced operating system for many things
command line interface user would going to be much slower than
6
be able to get something done faster someone who is working in a
than an advanced GUI user. command line.
Low Resources A computer that is only using the A GUI will require a lot more
command line takes a lot less of the system resources.
computer resources.
Event Driven Programming
Before knowing anything about event driven programming we must know what are events.
Events are the actions that are performed by the user during the application usage. If a
user clicks a mouse button on any object then the click event occurs. If the user moves the
mouse then the mouse move event occurs. By the same way an application can generate key
down event, key up event mouse double click event.
Any programming language which uses these events to run a specific portion of the program
will be called event driven programming. Games are the biggest example of these kinds of
application. The GUI based programs are all developed using event driven programming. The
other technology used in contrast to event driven programs is command driven programs where
using the command driven interface a user does each and every task.
The event driven programs are very user friendly and highly interactive systems. The command
driven programs are very difficult to operate and are not user friendly.
In practice an event can also be generated by timer so the software can appear to do something
spontaneously without an external event.
In this programming programmer does not specify how to create these objects, how to place
them on the screen and how to change their properties etc. the programmer just creates GUI by
using built in objects/controls and writes the code that responds to each event that occurs by
user interactions.
7
Handling Mouse Events
You can handle mouse events—such as mouse movements—in forms and controls; here are
the possible events for the Control class, which is a base class for controls and forms:
• MouseDown— Happens when the mouse pointer is over the control and a mouse
button is pressed.
• MouseEnter— Happens when the mouse pointer enters the control.
• MouseHover— Happens when the mouse pointer hovers over the control.
• MouseLeave— Happens when the mouse pointer leaves the control.
• MouseMove— Happens when the mouse pointer is moved over the control.
• MouseUp— Happens when the mouse pointer is over the control and a mouse button
is released.
• MouseWheel— Happens when the mouse wheel moves while the control has focus.
• KeyDown— Happens when a key is pressed down while the control has focus.
• KeyPress— Happens when a key is pressed while the control has focus.
• KeyUp— Happens when a key is released while the control has focus.
For KeyDown and KeyUp events, the event handler receives an argument of type
KeyEventArgs containing data related to this event, with these properties:
• Alt— Holds a value indicating whether the Alt key was pressed.
• Control— Holds a value indicating whether the Ctrl key was pressed.
• Handled— Holds or sets a value indicating whether the event was handled.
• KeyCode— Holds the keyboard code for a KeyDown or KeyUp event.
• KeyData— Holds the keyboard data for a KeyDown or KeyUp event.
• KeyValue— Holds the keyboard value for a KeyDown or KeyUp event.
• Modifiers— Holds the modifier flags for a KeyDown or KeyUp event. This indicates
which modifier keys (Ctrl, Shift, and/or Alt) were pressed. These values can be ORed
together (for more on the OR operator and how it works, see "Using Visual Basic
Operators" in Chapter 2)—using the Control, Shift, and Alt properties is usually easier.
8
• Shift— Holds a value indicating whether the Shift key was pressed.
For KeyPress events, you get an argument of type KeyPressEventArgs containing the
following KeyPressEventArgs properties:
• Handled— Gets or sets a value indicating whether the KeyPress event was handled.
If you set this value to True, Visual Basic will not handle this key (so if you want to
delete it, set Handled to True and do no further processing on it).
• KeyChar— Holds the character corresponding to the key pressed.
VB IDE (Integrated Development Environment)
There are so many independent windows in the IDE. The IDE windows are docking windows
1) The start page
The start page which is what you see when you first start visual basic. You can use the
start page to select from the recent projects. By default you can also create a new project
by clicking the new project button.
2) The menu system
After you have started visual basic and have seen the start page. You often turn to the
menu system to proceed as when you want to create a new project and use the
file/new/project menu item to bring up the new project dialog box.
3) Toolbars
Toolbars provide a quick way to select menu items because the toolbars buttons can be
quicker. E.g. To save the file you are currently working on you only need to click the
diskette button in the standard toolbar.
4) Toolbox
9
Toolbox consist number of controls which user can use to design the forms. You can
get the control on form by double clicking it in toolbox or we can drag and drop the
control on form from the toolbox.
5) Solution Explorer
This window gives you an overview of the solution you are working with. including all
the projects in it and the items in those projects.
6) Properties window
The properties window is another and favorite in visual basic. The properties window
is divided in to two columns. Text in the property of the left and their setting on the
right.
7) Output window
The output window gives you the results of building and running programs.
You can also send messages to the output window yourself if you use the
system.diagnostics.debug.write method.
Ex: system.diagnostics.debug.write (“hello from output window”)
Keywords
Keywords are the words whose meaning is already known by the compiler. In vb.net 350+
keywords are present.
*= / /= \ \=
^^= + += = -=
10
CStr CType CurDir Date DateAdd
11
NotOverridable Now NPer NPV Number
Year
12
Data Types
User- Sum of the sizes of its members. Each member of the structure has a range
Defined determined by its data type and independent of the ranges of the other members
Type
(structure)
13
Operators
Operators are the symbol to perform operation like addition, subtraction, multiplication,
division and so on.
Arithmetic operator
• ^ Exponentiation
• * Multiplication
• / Division
• \ Integer division
• Mod Modulus
• + Addition
• - Subtraction
Assignment operator
• = Assignment
• ^= Exponentiation followed by assignment
• *= Multiplication followed by assignment
• /= Division followed by assignment
• \= Integer division followed by assignment
• += Addition followed by assignment
• -= Subtraction followed by assignment
• &= Concatenation followed by assignment
Comparison operators
• < (Less than)—True if operand1 is less than operand2
• <= (Less than or equal to)—True if operand1 is less than or equal to operand2
• > (Greater than)—True if operand1 is greater than operand2
• >= (Greater than or equal to)—True if operand1 is greater than or equal to operand2
• = (Equal to)—True if operand1 equals operand2
• <> (Not equal to)—True if operand1 is not equal to operand2
• Is—True if two object references refer to the same object
• Like—Performs string pattern matching
Concatenation operators
• String concatenation
• + String concatenation
Logical/bitwise operators
14
• And— Performs an And operation (for logical operations: True if both operands are
True, False otherwise; the same for bit-by-bit operations where you treat 0 as False
and 1 as True).
• Not— Reverses the logical value of its operand, from True to False and False to True,
for bitwise operations, turns 0 into 1 and 1 into 0.
• Or— Operator performs an Or operation (for logical operations: True if either operand
is True, False otherwise; the same for bit-by-bit operations where you treat 0 as False
and 1 as True).
• Xor— Operator performs an exclusive-Or operation (for logical operations: True if
either operand, but not both, is True, and False otherwise; the same for bit-by-bit
operations where you treat 0 as False and 1 as True).
• AndAlso— Operator A "short circuited" And operator; if the first operand is False, the
second operand is not tested.
• OrElse— Operator A "short circuited" Or operator, if the first operand is True, the
second is not tested.
Variables
Variables are the names given to memory location. In vb.net variables are declared using Dim
keyword.
General syntax
Dim variable name As DataType
Ex:
Dim rno As Integer
Few more examples of variable declaration
Dim rno ‘declaring variable without data type (by default it takes object data type)
Dim rno As Integer
Dim str As string=”Deogiri” ‘declaring and initializing string variables
Dim rno As integer=10 ‘declaring and initializing integer variables
17
Decision control structure
A thing which we do in our daily life should be possible in programming. Ex: If I passed the
exam I will do the job otherwise I will again give the exam. Every condition has a result true
or false.
“Decision control structure is used to execute a part of program on the basis of condition true
or false” Here Passed the exam means Condition True and not means False.
In vb.net we implement decision control structure using following statements.
6) Simple if
7) If – else
8) Nested if – else
9) Else- if ladder
10) Select case
Simple if
Syntax example
If condition then Dim a as integer=150
Statements if a>100 then
End if WriteLine(“a is greater than 100”)
‘executes if condition is true
End if
Output
‘a is greater than 100
18
If-else
Syntax example
If condition then Dim a as integer=50
Statements If a>100 then
Else WriteLine(“a is greater than 100”)
Statements ‘executes if condition is true
End if Else
WriteLine(“a is less than 100”) ‘
executes if condition is false
End if
Output
‘a is less than 100
Nested if-else
Syntax example
If condition1 then ‘a=20
If condition2 then If a>100 then
Statements If a>200 then
Else WriteLine(“a is greater than 200”) ‘executes if
Statements condition2 is true
End if Else
End if WriteLine(“a is greater than 100 and less than 200”)
‘executes if condition2 is false
19
Else
WriteLine(“a is less than 100”) ‘executes if
condition1 is false
End if
Output
‘a is less than 100
Else-if ladder
Syntax example
If condition1 then ‘per=65
Statements If per>75 then
Else if condition2 then WriteLine(“ Distinction”) ‘executes if
Statements condition is true
Else if condition n then Else if per>60 then
Statements WriteLine(“ First Class”) ‘executes2 if
Else condition is true
Statements Else if per>50 then
End if WriteLine(“ Second Class”) ‘executes if
condition is true
Else if per>35 then
WriteLine(“ Third Class”) ‘executes if condition
is true
Else
WriteLine(“ Fail”) ‘executes if all conditions
are false
End if
Output First Class
20
Select case
The control statement that allows us to make a decision from the number of choices is called a
select case.
Here a CaseValue can be a integer or character constant followed by a case statements. Select
case statement matches the CaseValue with all cases if case is found that block is executed.
Syntax Example
Select case casevalue WriteLine(“enter roll number”)
Case casevalue1 ‘n= ReadLine()
Statements Select case n
Case casevalue2 Case 1
Statements WriteLine(“Ramesh”) ‘executes if n=1
Case casevalue3 Case 2
Statements WriteLine(“Mahesh”) ‘executes if n=2
Case casevaluen Case 3
Statements WriteLine(“Shyam”) ‘executes if n=3
Case else Case 4
Statements WriteLine(“Hanumant”) ‘executes if n=4
End select Case else
WriteLine(“Roll Number does not Exist”)
‘executes if n doesn’t match
End select
Output ‘enter roll number
3
Shyam
21
Looping Control structure
In our daily life we perform a series of actions again and again.
Ex: Sleeping, taking dinner, taking bath, Chatting with people etc.
Programming is also same like daily life. Here also we frequently need to perform an action
again and again and we make it possible using loop.
Repeating some portion of the program until the condition is being satisfied. This repetitive
operation is done using loop control structure.
A variable which are initialized by any value in the initialization is tested in the condition in
while loop. A block of while loop is repeatedly executed until the condition is false. When
condition will false the control will come out of loop. In the block of while a variable which
is initialized is incremented or decremented.
In vb.net we use following statements to perform looping control structure.
22
1) While
2) Do while
3) Do until
4) For
5) Nested for
While Loop
Syntax Example
‘
Output:
23
Do while
Syntax Example
24
Do until
Syntax Example
innitialization
do until condition
Statements
Increment/dicriment
Loop
Note :- while loop executes until the condition becomes false and Do until loop executes
until the condition becomes true.
25
Syntax Example
Syntax:
Nested For
Syntax Example
For var=initial value to final value step For i=1 to 2 step 1
For var=initial value to final value step For j=1 to 2 step 1
writeLine(“hello”)
Statements Next
Next writeLine(“India”)
Next
Statements Output
Next Hello
Hello
India
Hello
Hello
India
26
Array
“Array is a collection of same type of element.”
In VB.Net Array is divided in to two pars
1) Static Array
2) Dynamic Array
Static Array
You usually use the Dim statement to declare a standard array; here are a few examples of
standard array declarations:
Dim Data(30)
Dim Strings(10) As String
Dim TwoDArray(20, 40) As Integer
Dim Bounds(10, 100)
The Data array now has 30 elements, starting from Data(0), which is how you refer to the first
element, up to Data(29). 0 is the lower bound of this array, and 19 is the upper bound.
You can also initialize the data in an array if you don't give an array an explicit size; here's the
syntax to use, where I'm initializing an array with the values 10, 3, and 2:
Dim Data() = {10, 3, 2}.
Dynamic Array
You can use the Dim statement to declare an array with empty parentheses to declare a dynamic
array. Dynamic arrays can be dimensioned or redimensioned as you need them with the ReDim
statement (which you must also do the first time you want to use a dynamic array). Here's how
you use ReDim:
ReDim [Preserve] varname(subscripts)
You use the Preserve keyword to preserve the data in an existing array when you change the
size of the last dimension. The varname argument holds the name of the array to (re)dimension.
The subscripts term specifies the new dimension of the array.
This is one of those topics that is made easier with an example, so here's an example using
dynamic arrays, in which we declare an array, dimension it, and then redimension it:
Dim DynaStrings() As String
27
ReDim DynaStrings(10)
DynaStrings(0) = "String 0"
'Need more data space!
ReDim DynaStrings(100)
DynaStrings(50) = "String 50"
Collections
Collection is the collection of different type of elements. It is the object of collection class.
Like array collections size is not specified. Size of collection automatically grows ehrn you add
element in it and automatically shrinks when you remove element from it.
Creating Collection
Dim s As New Collection
s.Add(10)
s.Add(7.5)
s.Add(“Dinesh”)
Add procedure of collection class adds element in Collection
s.Remove(10)
s.RemoveAt(1)
Remove procedure of collection removes element from Collection and RemoveAt removes
the indexed element from the Collection.
S.Count
Returns total number of element from the collection
s.item(0)
returns 0th item from the collection.
Procedure
Procedures are made up of series of visual basic statements that when called are executed.
After the call is finished control returns to the statement that called the procedure.
There are two types of procedures in vb.net
28
3) Sub procedure
4) Functions
Sub Procedure
Sub procedures are the procedure which does not return the value.
Module module1
Sub main()
System.console.writeline(“hello visual basic”)
End sub
End module
We have placed all our executable code in the sub procedure named main. When this console
application starts control is transferred to the main sub procedure automatically and the code
in its run. However we can create our own sub procedures.
Sub display()
System.console.writeline(“hello visual basic”)
End sub
To execute the code in display you must call that sub procedure.
Sub main()
Display()
End sub
Sub display()
System.console.writeline(“hello visual basic”)
End sub
(You can also use call statement to call sub procedure like call display ())
Sub procedure with argument
Parenthesis following sub procedure is used to enclose data which are called arguments.
Eg we can define display with argument as follows
Here the keyword ByVal indicates that the text string is passed by value which means the copy
of the string is passed. This is the default in vb.net. The other possibility is ByRef which means
29
that the argument will be passed by reference. when you pass variable by reference the location
of the variable is passed to the procedure which means you have different access to that variable
block in the calling code.
Ex: passing argument to display
Sub main()
Display(“hello visual basic”)
End sub
Sub display(ByVal str as string)
Writeline(str)
End sub
This code will display our message as before.
Function
Function is a procedure which returns a value.
Declaring a function is much like declaring a sub procedure and specifies the return type of the
function instead of sub and specifies the return type of the function.
Note that you separate multiple arguments in the declaration of procedure with commas.
Ex: create a function display that accepts two integer arguments and return their sum
Function display(ByVal a as integer, ByVal b as integer) As integer
Return a+b
End function
When you call a function by using its name and an argument enclosed in parenthesis, that the
name is replaced by the value returned by function.
30
The following calling statement will print the addition
Sub main()
Dim s1,s2 As intiger
S1=10
S2=20
Writeline(“{0}+{1}={2}”,s1,s2,display(s1,s2))
End sub
Function display(ByVal a as intiger, ByVal b as intiger) As intiger
Return a+b
End function
We have used syntax in writeline that passing it a text string with terms like {0},{1}.{0} will
be replaced with first argument following the text string {1} with the second and so on when
you run this code you will see the following result.
10+20=30
Exception handling
31
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your
try block raises more than one exception in different situations.
Exception Classes in .Net Framework
In the .Net Framework, exceptions are represented by classes. The exception classes in .Net
Framework are mainly directly or indirectly derived from the System.Exception class. Some
of the exception classes derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application
programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
32
System.OutOfMemoryException Handles errors generated from insufficient free
memory.
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try
and catch blocks. Using these blocks the core program statements are separated from the error-
handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs −
Live Demo
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from
the ApplicationException class. The following example demonstrates this −
Live Demo
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
33
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception
class.
You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
The following program demonstrates this −
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
A custom exception is being thrown here...
Now inside the Finally Block
34
The Control Class
The Control class is in the System.Windows.Forms namespace. It serves as a base class for
the Windows controls we'll see—such as rich text boxes—which have this class hierarchy (that
is, the MarshalByRefObject class is derived from the Object class, and the Component class
is derived from the MarshalByRef Object class, and so on):
Object
MarshalByRefObject
Component
Control
TextBoxBase
RichTextBox
Because Windows controls are based on the Control class, they inherit many properties,
methods, and events from that class, so I'll list the more interesting ones here. (Keep in mind
that the Form class is also derived from Control, so it also shares these properties, methods,
and events). You can find noteworthy public properties of the Control class in Table 5.1,
noteworthy methods in Table 5.2, and events in Table 5.3.
Table 5.1: Noteworthy public properties of Control objects.
Property Means
AllowDrop Sets/gets a value specifying if the control can accept data dropped into
it.
Bottom Gets the distance between the bottom of the control and the top of its
container's client area.
CanFocus Returns a value specifying if the control can receive the focus.
Capture Sets/gets a value specifying if the control has captured the mouse.
35
Table 5.1: Noteworthy public properties of Control objects.
Property Means
CausesValidation Sets/gets a value specifying if the control causes validation for all
controls that require validation.
ContainsFocus Returns a value specifying if the control has the input focus.
Cursor Sets/gets the cursor displayed when the user moves the mouse pointer
over this control.
Location Sets/gets the coordinates of the upper-left corner of the control with
respect to the upper-left corner of its container.
Right Returns the distance between the right edge of the control and the left
edge of its container.
36
Table 5.1: Noteworthy public properties of Control objects.
Property Means
TabStop Sets/gets a value specifying if the user can tab to this control with the
Tab key.
Method Means
GetNextControl Retrieves the next control in the tab order of child controls.
Invalidate Invalidates a part of the control and sends a paint message to the control.
37
Table 5.2: Noteworthy public methods of Control objects.
Method Means
Refresh Forces the control to invalidate its client area and repaint itself (and any
child controls).
Event Means
38
Table 5.3: Noteworthy public events of Control objects.
Event Means
Disposed Represents the method which will handle the Disposed event
of a Component.
DragLeave Occurs when an object has been dragged into and out of the
control's bounds.
DragOver Occurs when an object has been dragged over the control's
bounds.
KeyDown Occurs when a key is pressed down while the control has focus.
KeyPress Occurs when a key is pressed while the control has focus.
KeyUp Occurs when a key is released while the control has focus.
Layout Occurs when a control has to lay out its child controls.
MouseDown Occurs when the mouse pointer is over the control and a mouse
button is pressed.
39
Table 5.3: Noteworthy public events of Control objects.
Event Means
MouseHover Occurs when the mouse pointer hovers over 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.
I've included Tables 5.1, 5.2, and 5.3 for reference sake, and it's really worth looking through
these tables, finding out, for example, what properties to use to change the background color
of a control (BackColor), what method makes a control invisible (Hide), what event handles
mouse button press events (MouseDown), and so on. Note that when listing the noteworthy
properties, methods, and events of Windows controls in similar tables in this and the next
chapters, I'm going to omit those inherited from the Control class, because there simply isn't
room to list them all. You'll find all those common Control properties, methods, and events in
Tables 5.1, 5.2, and 5.3.
40
An object is a type of user interface element you create on a Visual Basic form by using a
toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control
consists of three important elements −
• Properties which describe the object,
• Methods cause an object to do something and
• Events are what happens when an object does something.
Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting their properties.
A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore
Color.
Properties can be set at design time by using the Properties window or at run time by using
statements in the program code.
Object. Property = Value
Where
• Object is the name of the object you're customizing.
• Property is the characteristic you want to change.
• Value is the new property setting.
For example,
Form1.Caption = "Hello"
You can set any of the form properties using Properties Window. Most of the properties can
be set or read during application execution. You can refer to Microsoft documentation for a
complete list of properties associated with different controls and restrictions applied to them.
Control Methods
41
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
Control Events
An event is a signal that informs an application that something important has occurred. For
example, when a user clicks a control on a form, the form can raise a Click event and call a
procedure that handles the event. There are various types of events associated with a Form
like click, double click, close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You can see this
code by double clicking the code which will give you a complete list of the all events
associated with Form control −
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'event handler code goes here
End Sub
Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event.
Similar way, you can check stub code for click, double click. If you want to initialize some
variables like properties, etc., then you will keep such code inside Form1_Load() subroutine.
Here, important point to note is the name of the event handler, which is by default
Form1_Load, but you can change this name based on your naming convention you use in your
application programming.
Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The control
classes are defined in the System.Windows.Forms namespace.
The following table lists some of the commonly used controls −
1 Forms
The container for all the controls that make up the user interface.
2
TextBox
It represents a Windows text box control.
3
Label
It represents a standard Windows label.
42
4
Button
It represents a Windows button control.
5
ListBox
It represents a Windows control to display a list of items.
6
ComboBox
It represents a Windows combo box control.
7
RadioButton
It enables the user to select a single option from a group of choices when paired
with other RadioButton controls.
8
CheckBox
It represents a Windows CheckBox.
9
PictureBox
It represents a Windows picture box control for displaying an image.
10
ProgressBar
It represents a Windows progress bar control.
11
ScrollBar
It Implements the basic functionality of a scroll bar control.
12
DateTimePicker
It represents a Windows control that allows the user to select a date and a time
and to display the date and time with a specified format.
13
TreeView
It displays a hierarchical collection of labeled items, each represented by a
TreeNode.
14
ListView
43
It represents a Windows list view control, which displays a collection of items
that can be displayed using one of four different views.
Let's start with creating a Window Forms Application by following the following steps in
Microsoft Visual Studio - File → New Project → Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays following
window Form with a name Form1.
Visual Basic Form is the container for all the controls that make up the user interface. Every
window you see in a running visual basic application is a form, thus the terms form and
window describe the same entity. Visual Studio creates a default form for you when you create
a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be
buttons to close, maximize and minimize the form shown below −
44
If you click the icon on the top left corner, it opens the control menu, which contains the
various commands to control the form like to move control from one place to another place,
to maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These properties
can be set or read during application execution. You can refer to Microsoft documentation for
a complete list of properties associated with a Form control −
2
CancelButton The button that's automatically activated when you hit the
Esc key.
Usually, the Cancel button on a form is set as CancelButton
for a form.
45
3
AutoScale This Boolean property determines whether the controls you
place on the form are automatically scaled to the height of
the current font. The default value of this property is True.
This is a property of the form, but it affects the controls on
the form.
4
AutoScroll This Boolean property indicates whether scroll bars will be
automatically attached to the form if it is resized to a point
that not all its controls are visible.
5
AutoScrollMinSize This property lets you specify the minimum size of the form,
before the scroll bars are attached.
6
AutoScrollPosition The AutoScrollPosition is the number of pixels by which the
two scroll bars were displaced from their initial locations.
7
BackColor Sets the form background color.
8
BorderStyle The BorderStyle property determines the style of the form's
border and the appearance of the form −
• None − Borderless window that can't be resized.
• Sizable − This is default value and will be used for
resizable window that's used for displaying regular
forms.
• Fixed3D − Window with a visible border, "raised"
relative to the main area. In this case, windows can't
be resized.
• FixedDialog − A fixed window, used to create dialog
boxes.
• FixedSingle − A fixed window with a single line
border.
• FixedToolWindow − A fixed window with a Close
button only. It looks like the toolbar displayed by the
drawing and imaging applications.
• SizableToolWindow − Same as the
FixedToolWindow but resizable. In addition, its
caption font is smaller than the usual.
46
9
ControlBox By default, this property is True and you can set it to False
to hide the icon and disable the Control menu.
10
Enabled If True, allows the form to respond to mouse and keyboard
events; if False, disables form.
11
Font This property specify font type, style, size
12
HelpButton Determines whether a Help button should be displayed in the
caption box of the form.
13
Height This is the height of the Form in pixels.
14
MinimizeBox By default, this property is True and you can set it to False
to hide the Minimize button on the title bar.
15
MaximizeBox By default, this property is True and you can set it to False
to hide the Maximize button on the title bar.
16
MinimumSize This specifies the minimum height and width of the window
you can minimize.
17
MaximumSize This specifies the maximum height and width of the window
you maximize.
18
Name This is the actual name of the form.
19
StartPosition This property determines the initial position of the form
when it's first displayed. It will have any of the following
values −
• CenterParent − The form is centered in the area of
its parent form.
• CenterScreen − The form is centered on the monitor.
• Manual − The location and size of the form will
determine its starting position.
47
• WindowsDefaultBounds − The form is positioned
at the default location and size determined by
Windows.
• WindowsDefaultLocation − The form is positioned
at the Windows default location and has the
dimensions you've set at design time.
20
Text The text, which will appear at the title bar of the form.
21
Top, Left These two properties set or return the coordinates of the
form's top-left corner in pixels.
22
TopMost This property is a True/False value that lets you specify
whether the form will remain on top of all other forms in
your application. Its default property is False.
23
Width This is the width of the form in pixel.
Form Methods
The following are some of the commonly used methods of the Form class. You can refer to
Microsoft documentation for a complete list of methods associated with forms control −
1 Activate
Activates the form and gives it focus.
2
ActivateMdiChild
Activates the MDI child of a form.
3
AddOwnedForm
Adds an owned form to this form.
4
BringToFront
Brings the control to the front of the z-order.
48
5
CenterToParent
Centers the position of the form within the bounds of the parent form.
6
CenterToScreen
Centers the form on the current screen.
7
Close
Closes the form.
8
Contains
Retrieves a value indicating whether the specified control is a child of the control.
9
Focus
Sets input focus to the control.
10
Hide
Conceals the control from the user.
11
Refresh
Forces the control to invalidate its client area and immediately redraw itself and
any child controls.
12
Scale(SizeF)
Scales the control and all child controls by the specified scaling factor.
13
ScaleControl
Scales the location, size, padding, and margin of a control.
14
ScaleCore
Performs scaling of the form.
15
Select
Activates the control.
49
16
SendToBack
Sends the control to the back of the z-order.
17
SetAutoScrollMargin
Sets the size of the auto-scroll margins.
18
SetDesktopBounds
Sets the bounds of the form in desktop coordinates.
19
SetDesktopLocation
Sets the location of the form in desktop coordinates.
20
SetDisplayRectLocation
Positions the display window to the specified value.
21
Show
Displays the control to the user.
22
ShowDialog
Shows the form as a modal dialog box.
Form Events
Following table lists down various important events related to a form. You can refer to
Microsoft documentation for a complete list of events associated with forms control −
2
Click Occurs when the form is clicked.
3
Closed Occurs before the form is closed.
50
4
Closing Occurs when the form is closing.
5
DoubleClick Occurs when the form control is double-clicked.
6
DragDrop Occurs when a drag-and-drop operation is completed.
7
Enter Occurs when the form is entered.
8
GotFocus Occurs when the form control receives focus.
9
HelpButtonClicked Occurs when the Help button is clicked.
10
KeyDown Occurs when a key is pressed while the form has focus.
11
KeyPress Occurs when a key is pressed while the form has focus.
12
KeyUp Occurs when a key is released while the form has
focus.
13
Load Occurs before a form is displayed for the first time.
14
LostFocus Occurs when the form loses focus.
15
MouseDown Occurs when the mouse pointer is over the form and a
mouse button is pressed.
16
MouseEnter Occurs when the mouse pointer enters the form.
17
MouseHover Occurs when the mouse pointer rests on the form.
18
MouseLeave Occurs when the mouse pointer leaves the form.
51
20
MouseUp Occurs when the mouse pointer is over the form and a
mouse button is released.
21
MouseWheel Occurs when the mouse wheel moves while the control
has focus.
22
Move Occurs when the form is moved.
23
Resize Occurs when the control is resized.
24
Scroll Occurs when the user or code scrolls through the client
area.
25
Shown Occurs whenever the form is first displayed.
26
VisibleChanged Occurs when the Visible property value changes.
Text box controls allow entering text on a form at runtime. By default, it takes a single line of
text, however, you can make it accept multiple texts and even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on
the form.
52
The following are some of the commonly used properties of the TextBox control −
1 AcceptsReturn
Gets or sets a value indicating whether pressing ENTER in a multiline TextBox
control creates a new line of text in the control or activates the default button for
the form.
2
AutoCompleteCustomSource
Gets or sets a custom System.Collections.Specialized.StringCollection to use
when the AutoCompleteSourceproperty is set to CustomSource.
3
AutoCompleteMode
Gets or sets an option that controls how automatic completion works for the
TextBox.
4
AutoCompleteSource
Gets or sets a value specifying the source of complete strings used for automatic
completion.
5
CharacterCasing
Gets or sets whether the TextBox control modifies the case of characters as they
are typed.
6
Font
Gets or sets the font of the text displayed by the control.
7
FontHeight
Gets or sets the height of the font of the control.
8
ForeColor
Gets or sets the foreground color of the control.
9
Lines
Gets or sets the lines of text in a text box control.
53
10
Multiline
Gets or sets a value indicating whether this is a multiline TextBox control.
11
PasswordChar
Gets or sets the character used to mask characters of a password in a single-line
TextBox control.
12
ReadOnly
Gets or sets a value indicating whether text in the text box is read-only.
13
ScrollBars
Gets or sets which scroll bars should appear in a multiline TextBox control. This
property has values −
• None
• Horizontal
• Vertical
• Both
14
TabIndex
Gets or sets the tab order of the control within its container.
15
Text
Gets or sets the current text in the TextBox.
16
TextAlign
Gets or sets how text is aligned in a TextBox control. This property has values −
• Left
• Right
• Center
17
TextLength
Gets the length of text in the control.
18
WordWrap
54
Indicates whether a multiline text box control automatically wraps words to the
beginning of the next line when necessary.
The following are some of the commonly used methods of the TextBox control −
1 AppendText
Appends text to the current text of a text box.
2
Clear
Clears all text from the text box control.
3
Copy
Copies the current selection in the text box to the Clipboard.
4
Cut
Moves the current selection in the text box to the Clipboard.
5
Paste
Replaces the current selection in the text box with the contents of the Clipboard.
6
Paste(String)
Sets the selected text to the specified text without clearing the undo buffer.
7
ResetText
Resets the Text property to its default value.
8
ToString
Returns a string that represents the TextBoxBase control.
9
Undo
55
Undoes the last edit operation in the text box.
The following are some of the commonly used events of the Text control −
1 Click
Occurs when the control is clicked.
2
DoubleClick
Occurs when the control is double-clicked.
3
TextAlignChanged
Occurs when the TextAlign property value changes.
Example
In this example, we create three text boxes and use the Click event of a button to display the
entered text using a message box. Take the following steps −
• Drag and drop three Label controls and three TextBox controls on the form.
• Change the texts on the labels to: Name, Organization and Comments, respectively.
• Change the names of the text boxes to txtName, txtOrg and txtComment, respectively.
• Drag and drop a button control on the form. Set its name to btnMessage and its text
property to 'Send Message'.
• Click the button to add the Click event in the code window and add the following code.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
56
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Clicking the Send Message button would show the following message box −
The Label control represents a standard Windows label. It is generally used to display some
informative text on the GUI which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it on the form.
57
Properties of the Label Control
The following are some of the commonly used properties of the Label control −
1 Autosize
Gets or sets a value specifying if the control should be automatically resized to
display all its contents.
2
BorderStyle
Gets or sets the border style for the control.
3
FlatStyle
Gets or sets the flat style appearance of the Label control
4
Font
Gets or sets the font of the text displayed by the control.
5
FontHeight
Gets or sets the height of the font of the control.
6
ForeColor
Gets or sets the foreground color of the control.
7
PreferredHeight
Gets the preferred height of the control.
8
PreferredWidth
Gets the preferred width of the control.
9
TabStop
Gets or sets a value indicating whether the user can tab to the Label. This property
is not used by this class.
58
10
Text
Gets or sets the text associated with this control.
11
TextAlign
Gets or sets the alignment of text in the label.
The following are some of the commonly used methods of the Label control −
1 GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted.
2
Refresh
Forces the control to invalidate its client area and immediately redraw itself and
any child controls.
3
Select
Activates the control.
4
Show
Displays the control to the user.
5
ToString
Returns a String that contains the name of the control.
The following are some of the commonly used events of the Label control −
1
AutoSizeChanged
59
Occurs when the value of the AutoSize property changes.
2
Click
Occurs when the control is clicked.
3
DoubleClick
Occurs when the control is double-clicked.
4
GotFocus
Occurs when the control receives focus.
5
Leave
Occurs when the input focus leaves the control.
6
LostFocus
Occurs when the control loses focus.
7
TabIndexChanged
Occurs when the TabIndex property value changes.
8
TabStopChanged
Occurs when the TabStop property changes.
9
TextChanged
Occurs when the Text property value changes.
Consult Microsoft documentation for detailed list of properties, methods and events of the
Label control.
Example
Following is an example, which shows how we can create two labels. Let us create the first
label from the designer view tab and set its properties from the properties window. We will
use the Click and the DoubleClick events of the label to move the first label and change its
text and create the second label and add it to the form, respectively.
Take the following steps −
• Drag and drop a Label control on the form.
60
• Set the Text property to provide the caption "This is a Label Control".
• Set the Font property from the properties window.
• Click the label to add the Click event in the code window and add the following codes.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
' Set window width and height
Me.Height = 300
Me.Width = 560
61
Clicking and double clicking the label would produce the following effect −
RadioButton Control
The RadioButton control is used to provide a set of mutually exclusive options. The user can
select one radio button in a group. If you need to place more than one group of radio buttons
in the same form, you should place them in different container controls like a GroupBox
control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and
dropping on the form.
62
The Checked property of the radio button is used to set the state of a radio button. You can
display text, image or both on radio button control. You can also change the appearance of the
radio button control by using the Appearance property.
Properties of the RadioButton Control
The following are some of the commonly used properties of the RadioButton control −
1 Appearance
Gets or sets a value determining the appearance of the radio button.
2 AutoCheck
Gets or sets a value indicating whether the Checked value and the appearance of
the control automatically change when the control is clicked.
3 CheckAlign
Gets or sets the location of the check box portion of the radio button.
4 Checked
Gets or sets a value indicating whether the control is checked.
5
Text
63
Gets or sets the caption for a radio button.
6 TabStop
Gets or sets a value indicating whether a user can give focus to the RadioButton
control using the TAB key.
1 PerformClick
Generates a Click event for the control, simulating a click by a user.
1 AppearanceChanged
Occurs when the value of the Appearance property of the RadioButton control is
changed.
2
CheckedChanged
Occurs when the value of the Checked property of the RadioButton control is
changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the
RadioButton control.
Example
In the following example, let us create two groups of radio buttons and use their
CheckedChanged events for changing the BackColor and ForeColor property of the form.
64
Let's double click on the radio buttons and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
65
e As EventArgs) Handles RadioButton6.CheckedChanged
Me.ForeColor = Color.Red
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
The CheckBox control allows the user to set true/false or yes/no type options. The user can
select or deselect it. When a check box is selected it has the value True, and when it is cleared,
it holds the value False.
Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping
on the form.
66
The CheckBox control has three states, checked, unchecked and indeterminate. In the
indeterminate state, the check box is grayed out. To enable the indeterminate state,
the ThreeState property of the check box is set to be True.
Properties of the CheckBox Control
The following are some of the commonly used properties of the CheckBox control −
1 Appearance
Gets or sets a value determining the appearance of the check box.
2 AutoCheck
Gets or sets a value indicating whether the Checked or CheckedState value and
the appearance of the control automatically change when the check box is
selected.
3 CheckAlign
Gets or sets the horizontal and vertical alignment of the check mark on the check
box.
4 Checked
Gets or sets a value indicating whether the check box is selected.
67
5 CheckState
Gets or sets the state of a check box.
6 Text
Gets or sets the caption of a check box.
7 ThreeState
Gets or sets a value indicating whether or not a check box should allow three
check states rather than two.
1 OnCheckedChanged
Raises the CheckedChanged event.
2 OnCheckStateChanged
Raises the CheckStateChanged event.
3 OnClick
Raises the OnClick event.
1 AppearanceChanged
Occurs when the value of the Appearance property of the check box is changed.
2 CheckedChanged
Occurs when the value of the Checked property of the CheckBox control is
changed.
68
3 CheckStateChanged
Occurs when the value of the CheckState property of the CheckBox control is
changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the
CheckBox control.
Example
In this example, let us add four check boxes in a group box. The check boxes will allow the
users to choose the source from which they came to know about the organization. If the user
chooses the check box with text "others", then the user is asked to specify and a text box is
provided to give input. When the user clicks the Submit button, he/she gets an appropriate
message.
The form in design view −
69
If CheckBox1.Checked = True Then
str &= CheckBox1.Text
str &= " "
End If
70
Clicking the Submit button −
The PictureBox control is used for displaying images on the form. The Image property of the
control allows you to set an image both at design time or at run time.
Let's create a picture box by dragging a PictureBox control from the Toolbox and dropping it
on the form.
71
Properties of the PictureBox Control
The following are some of the commonly used properties of the PictureBox control −
1 AllowDrop
Specifies whether the picture box accepts data that a user drags on it.
2 ErrorImage
Gets or specifies an image to be displayed when an error occurs during the image-
loading process or if the image load is cancelled.
3
Image
Gets or sets the image that is displayed in the control.
4 ImageLocation
Gets or sets the path or the URL for the image displayed in the control.
5 InitialImage
Gets or sets the image displayed in the control when the main image is loaded.
72
6 SizeMode
Determines the size of the image to be displayed in the control. This property
takes its value from the PictureBoxSizeMode enumeration, which has values −
• Normal − the upper left corner of the image is placed at upper left part of
the picture box
• StrechImage − allows stretching of the image
• AutoSize − allows resizing the picture box to the size of the image
• CenterImage − allows centering the image in the picture box
• Zoom − allows increasing or decreasing the image size to maintain the
size ratio.
7 TabIndex
Gets or sets the tab index value.
8 TabStop
Specifies whether the user will be able to focus on the picture box by using the
TAB key.
9 Text
Gets or sets the text for the picture box.
10 WaitOnLoad
Specifies whether or not an image is loaded synchronously.
1 CancelAsync
Cancels an asynchronous image load.
2 Load
Displays an image in the picture box
73
3 LoadAsync
Loads image asynchronously.
4 ToString
Returns the string that represents the current picture box.
1 CausesValidationChanged
Overrides the Control.CausesValidationChanged property.
2 Click
Occurs when the control is clicked.
3 Enter
Overrides the Control.Enter property.
4 FontChanged
Occurs when the value of the Font property changes.
5 ForeColorChanged
Occurs when the value of the ForeColor property changes.
6 KeyDown
Occurs when a key is pressed when the control has focus.
7
KeyPress
Occurs when a key is pressed when the control has focus.
8 KeyUp
Occurs when a key is released when the control has focus.
74
9 Leave
Occurs when input focus leaves the PictureBox.
10 LoadCompleted
Occurs when the asynchronous image-load operation is completed, been
canceled, or raised an exception.
11 LoadProgressChanged
Occurs when the progress of an asynchronous image-loading operation has
changed.
12 Resize
Occurs when the control is resized.
13 RightToLeftChanged
Occurs when the value of the RightToLeft property changes.
14 SizeChanged
Occurs when the Size property value changes.
15 SizeModeChanged
Occurs when SizeMode changes.
16 TabIndexChanged
Occurs when the value of the TabIndex property changes.
17 TabStopChanged
Occurs when the value of the TabStop property changes.
18
TextChanged
Occurs when the value of the Text property changes.
75
Example
In this example, let us put a picture box and a button control on the form. We set the image
property of the picture box to logo.png, as we used before. The Click event of the button
named Button1 is coded to stretch the image to a specified size −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
76
Clicking on the button results in −
The DateTimePicker control allows selecting a date and time by editing the displayed values
in the control. If you click the arrow in the DateTimePicker control, it displays a month
calendar, like a combo box control. The user can make selection by clicking the required date.
The new selected value appears in the text box part of the control.
77
The MinDate and the MaxDate properties allow you to put limits on the date range.
Properties of the DateTimePicker Control
The following are some of the commonly used properties of the DateTimePicker control −
1 BackColor
Gets or sets a value indicating the background color of the DateTimePicker
control.
2 BackgroundImage
Gets or sets the background image for the control.
3 BackgroundImageLayout
Gets or sets the layout of the background image of the DateTimePicker control.
4 CalendarFont
Gets or sets the font style applied to the calendar.
5 CalendarForeColor
Gets or sets the foreground color of the calendar.
78
6 CalendarMonthBackground
Gets or sets the background color of the calendar month.
7 CalendarTitleBackColor
Gets or sets the background color of the calendar title.
8 CalendarTitleForeColor
Gets or sets the foreground color of the calendar title.
9 CalendarTrailingForeColor
Gets or sets the foreground color of the calendar trailing dates.
10 Checked
Gets or sets a value indicating whether the Value property has been set with a
valid date/time value and the displayed value is able to be updated.
11 CustomFormat
Gets or sets the custom date/time format string.
12 DropDownAlign
Gets or sets the alignment of the drop-down calendar on the DateTimePicker
control.
13 ForeColor
Gets or sets the foreground color of the DateTimePicker control.
14 Format
Gets or sets the format of the date and time displayed in the control.
15
MaxDate
Gets or sets the maximum date and time that can be selected in the control.
16 MaximumDateTime
Gets the maximum date value allowed for the DateTimePicker control.
79
17 MinDate
Gets or sets the minimum date and time that can be selected in the control.
18 MinimumDateTime
Gets the minimum date value allowed for the DateTimePicker control.
19 PreferredHeight
Gets the preferred height of the DateTimePicker control.
20 RightToLeftLayout
Gets or sets whether the contents of the DateTimePicker are laid out from right
to left.
21 ShowCheckBox
Gets or sets a value indicating whether a check box is displayed to the left of the
selected date.
22 ShowUpDown
Gets or sets a value indicating whether a spin button control (also known as an
up-down control) is used to adjust the date/time value.
23 Text
Gets or sets the text associated with this control.
24 Value
Gets or sets the date/time value assigned to the control.
1 ToString
Returns the string representing the control.
80
Events of the DateTimePicker Control
The following are some of the commonly used events of the DateTimePicker control −
1 BackColorChanged
Occurs when the value of the BackColor property changes.
2 BackgroundImageChanged
Occurs when the value of the BackgroundImage property changes.
3 BackgroundImageLayoutChanged
Occurs when the value of the BackgroundImageLayout property changes.
4 Click
Occurs when the control is clicked.
5 CloseUp
Occurs when the drop-down calendar is dismissed and disappears.
6 DoubleClick
Occurs when the control is double-clicked.
7 DragDrop
Occurs when a drag-and-drop operation is completed.
8 ForeColorChanged
Occurs when the value of the ForeColor property changes.
9 FormatChanged
Occurs when the Format property value has changed.
10 MouseClick
Occurs when the control is clicked with the mouse.
81
11 MouseDoubleClick
Occurs when the control is double-clicked with the mouse.
12 PaddingChanged
Occurs when the value of the Padding property changes.
13 Paint
Occurs when the control is redrawn.
14 RightToLeftLayoutChanged
Occurs when the RightToLeftLayout property changes.
15 TextChanged
Occurs when the value of the Text property changes.
16 ValueChanged
Occurs when the Value property changes.
Example
In this example, let us create a small application for calculating days of leave. Let us add two
DateTimePicker controls on the form, where the user will enter the date of going on leave and
the date of joining. Let us keep a button control for performing the calculation and appropriate
label controls for displaying information.
The form in design view −
82
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Select two dates and click on the button for leave calculation −
83
When you define a class, you define a blueprint for a data type. This doesn't actually define
any data, but it does define what the class name means, that is, what an object of the class will
consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class
body, ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
• attributelist is a list of attributes that apply to the class. Optional.
• accessmodifier defines the access levels of the class, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
• Shadows indicate that the variable re-declares and hides an identically named element,
or set of overloaded elements, in a base class. Optional.
• MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
• NotInheritable specifies that the class cannot be used as a base class.
• Partial indicates a partial definition of the class.
• Inherits specifies the base class it is inheriting from.
• Implements specifies the interfaces the class is inheriting from.
The following example demonstrates a Box class, with three data members, length, breadth
and height −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
84
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the
class definition like any other variable. It operates on any object of the class of which it is a
member and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.
Let us put above concepts to set and get the value of different class members in a class −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
85
height = hei
End Sub
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Constructors and Destructors
A class constructor is a special member Sub of a class that is executed whenever we create
new objects of that class. A constructor has the name New and it does not have any return
type.
Following program explains the concept of constructor −
Live Demo
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub
86
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
87
When the above code is compiled and executed, it produces the following result −
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its
class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out of the
program like closing files, releasing memories, etc.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor −
Live Demo
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
88
Shared Members of a VB.Net Class
We can define class members as static using the Shared keyword. When we declare a member
of a class as Shared, it means no matter how many objects of the class are created, there is
only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared
variables are used for defining constants because their values can be retrieved by invoking the
class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can
also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared
variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members −
Live Demo
Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Value of variable num: 3
Inheritance
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to as
the derived class.
89
Base & Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit
data and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −
Live Demo
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Length: 4.5
91
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.
92