0% found this document useful (0 votes)
40 views

Unit - 2 VB

VB.NET is a simple, object-oriented programming language that is a successor to Visual Basic 6.0. It is implemented on the .NET framework and supports OOP concepts like abstraction, encapsulation, inheritance, and polymorphism. All data types and objects in VB.NET inherit from a base class. VB.NET allows developing Windows, web, and mobile applications. It features rapid application development, an intuitive interface, and is not case sensitive.

Uploaded by

jeeshu048
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Unit - 2 VB

VB.NET is a simple, object-oriented programming language that is a successor to Visual Basic 6.0. It is implemented on the .NET framework and supports OOP concepts like abstraction, encapsulation, inheritance, and polymorphism. All data types and objects in VB.NET inherit from a base class. VB.NET allows developing Windows, web, and mobile applications. It features rapid application development, an intuitive interface, and is not case sensitive.

Uploaded by

jeeshu048
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Unit-2

VB.NET

The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-level,
object-oriented programming language developed by Microsoft in 2002. It is a successor of
Visual Basic 6.0, that is implemented on the Microsoft .NET framework. Furthermore, it
supports the OOPs concept, such as abstraction, encapsulation, inheritance, and polymorphism.
Therefore, everything in the VB.NET language is an object, including all primitive data types
(Integer, String, char, long, short, Boolean, etc.), user-defined data types, events, and all objects
that inherit from its base class. It is not a case sensitive language, whereas, C++, Java, and C# are
case sensitive language.

Applications built using the VB.NET language are very reliable and scalable, relying on the
.NET Framework to access all libraries that help to execute a VB.NET program. With this
language, you can develop a fully object-oriented application that is similar to an application
created through another language such as C++, Java, or C#. In addition, applications or programs
of VB.NET are not only running on the window operating system but can also run on Linux or
Mac OS.

VB.NET Features

As we know, it is a high-level programming language with many features to develop a


secure and robust application. These are the following features that make it the most
popular programming language.

o It is an object-oriented programming language that follows various oops


concepts such as abstraction, encapsulation, inheritance, and many more. It
means that everything in VB.NET programming will be treated as an object.
o This language is used to design user interfaces for window, mobile, and web-
based applications.
o It supports a rapid application development tool kit. In which a developer does
not need to write all the codes as it can get various code automatically from its
libraries. For example, when we create a form in Visual basic.net, it
automatically calls events of various form in that class.
o It is not a case sensitive language like other languages such as C++, java, etc.
o It supports Boolean condition for decision making in programming.
o It also supports the multithreading concept, in which you can do multiple tasks
at the same time.
o It provides simple events management in .NET application.
o A Window Form enables us to inherit all existing functionality of form that can
be used to create a new form. So, in this way, it reduced the code complexity.
o It uses an external object as a reference that can be used in a VB.NET
application.
o Automatic initialized a garbage collection.
o It follows a structured and extensible programming language for error detection
and recovery.
o Conditional compilation and easy to use generic classes.
o It is useful to develop web, window, and mobile applications.

Creating a new project


When we start VB we will see a window we have to select the project type which we want to be
open

Creating a windows application


To create an application based on windows form, select the new item in the file menu then select the
project item in the sub menu that appears. This brings up a new project dialog box. Select the folder
labeled visual basic project in the project types box and select the windows based application project
type in template box .you also can name the new project

Working With forms


The appearance of form:-
The most basic object in VB in the form object. Which is the visual Foundation of our
application if is basically a window on which we can add different element in order to create a
complete application. The form object has the various parts.
1. FormBorderStyle : - the formBorderStyle is the boundary is form .we can set the border of the
form with the border style of the form. it has three options Fixed ,sizable , and non existence .
2. Title Bar: - the titled bar is colored bar on the top of the form. we can use the title bar to drag
the window around the screen.
3. Text:-the form s text is the text we see on the form .we can use the title bar .it can be use to
identify the name of application.
4. Control Menu: - the control menu is simple menu that allow us to simple restore, move, resize,
minimize, maximize and close form.
5. Maximize Button: - the maximize button has two purpose .if the form has normal state then we
can click maximize button to automatically expand the form. If he form is maximized then we
can click this button to restore the form to its original size.
6. Minimize Button: - is used to minimize the current form.
7. Close button. Is used to close the current form.
Element of user Interface
The user interface is the screen which appears when the programs run. it consist of various
elements which the user can interact and controls the application .the fist element of the user
interface is the form .this is the windows display at the run time and act as container for all the
elements of the interface.

1. Picture Box:-With the Windows Forms PictureBox control, you can load and display a picture
on a form at design time by setting the Image property to a valid picture. Acceptable file types
include:

Type File Extension

Bitmap .bmp

Icon .ico

GIF .gif

Metafile .wmf

JPEG .jpg

To display a picture at design time

1. Draw a PictureBox control on a form.


2. On the Properties window, select the Image property, then click the ellipsis button
to display the Open dialog box.
3. If you are looking for a specific file type (for example, .gif files), select it in the Files
of type box.
4. Select the file you want to display.
2 Label:- This control display text that use can not edit , set the label text with text property
1. Text box:- This control display text that use can edit , the text box control is mini text editors
and its most important property is the text property.
2. Shape this control use to draw boxes on the form and to group other elements
3. Command Button:- This the most common element of the window interface. A command
button represents o action that is done when the user clicks the button.
4. Check Box .check box control represent more the one choices that the user can select .the
check box control is main property is the value it is 0 if the check box is cleared and 1 then
check box is selected .
5. Option Button:- option s buttons or radio button appears in a groups and user can choose an
item from the list on enter a new string in the edit field.
6. List box :- controls contain a list of items from which the user can choose one or more items
7. Drive List Box:- this folder is to display of all folders in the current drive and sleets the user
directory of the current drive.
8. Horizontal and vertical scroll bars:- the horizontal and vertical scroll bar let the user specify a
value of scrolling the controls button between the minimum and maximum value.
9. Timer: - we can use this control to perform the task s at regular intervals . the main property of
the timer control is INTERVAL.
10. Drive List Box this control is used to display a list off all all the folders in current drive and lets
the user to select directory of the current drive.
11. File list box. This control is used to display a list of all files in the current folder.
12. OLE. This control is used to display other windows based application.
13. TreeView : Displays a hierarchy of nodes.
14. ToolBar : Toolbar for your Application.
15. Statusbar : Display various types by information
16. SaveFileDialog:Dialog box for saving files
17. Rich text box:Display’s rich text files on a form
18. PrintDialog : Dialog box for printing
19. Main menu: menu for your program
20. Month Calendar: display and sets numeric values
21. Link Label: web site link for your programs.
22. Open File Dialog: dialog box for openings file
23. Group Box: provider grouping for other controls.
24. Help Provider: used to associate a hypertext markup language (html) help file.
25. Font Display: dialog box for fonts
26. Context Menu: Gives users access to frequently used menu commands.
27. CrystalReportMenu: Allow user Crystal Report to be viewed in an application.
28. DataGrid: Displays data in a tabular view.
29. DateTimePicker: Choose a single item from date/time.
30. ColorDialog: Dialog that allow users to choose colors.
Variable :-
A Variable is a named container of data that represents a storage location that is used to store
data value. A Variable may take different values at different times during the execution of program.
The Rules for variable name:

1. Variable must begin with a letter (not underscore).


2. They may contain any mixture of letters not numbers.
3. They may not include punctuation or other symbol except underscore.
4. They may not have more than 255 characters.

Dim Statement
Declaration of Variable

[Public|Protected|Private|Static] Dim Varname As [ New ] type [ = initexpr ]

Parts

Public

Optional. Variables declared with the Public keyword have public access. There are no
restrictions on the accessibility of public variables.

You can use Public only at module, namespace, or file level. This means you can declare
public variables in a source file or inside a module, class, or structure, but not inside a
procedure. If you specify Public, you can optionally omit the Dim keyword.

Protected

Optional. Variables declared with the Protected keyword have protected access. They are
accessible only from within their own class or from a derived class. Protected access is not a
superset of friend access.

You can use Protected only at class level. This means you can declare protected
variables inside a class but not inside a procedure, and not at module, namespace, or file
level. You can use Protected only to declare members of the class. If you specify
Protected, you can optionally omit the Dim keyword.

Private

Optional. Variables declared with the Private keyword have private access. They are accessible
only from within their declaration context, including from members of any nested types such as
procedures.

You can use Private only at module level. This means you can declare private variables
inside a module, class, or structure, but not at namespace or file level and not inside a
procedure. If you specify Private, you can optionally omit the Dim keyword.
Static

Optional. Variables declared with the Static keyword remain in existence and retain their latest
values after termination of the procedure in which they are declared.

You can use Static only at procedure level. This means you can declare static variables
inside a procedure or a block within a procedure, but not at class or module level. If you
specify Static, you can optionally omit the Dim keyword.

You cannot specify Static together with either Shared or Shadows in the same variable
declaration.

varname

Required. Name of the variable. Must be a valid Visual Basic identifier. You can declare as many
variables as you like in the same declaration statement, specifying the name part for each one
and supplying the boundlist part for arrays. Multiple variables are separated by commas.

You can declare several variables to be of the same data type. You can also specify
different types for different variables or groups of variables. Each variable takes the data
type specified in the first As clause encountered after its name part.

New

Optional. Keyword that enables immediate creation of an object. If you use New when declaring
the object variable, a new instance of the object is created when the Dim statement is executed.

type

Optional unless Option Strict is On. Data type of the variable. Can be Boolean, Byte, Char, Date,
Decimal, Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration,
structure, class, or interface. You can use a separate As clause for each variable being defined,
or you can define several variables to be of the same type by using a common As clause.

Life Time and Scope of Variable


Variables declared with Dim are available to all code within the region containing the Dim
statement. If they are declared in a module, class, or structure, but outside any procedure, they
can be accessed from anywhere within that module, class, or structure. If they are declared inside
a procedure or a block, they are accessible only from within that procedure or block. To specify
their accessibility in more detail, include the Public, Protected, Friend, Protected Friend,
Private, or Static keywords.

The Dim statement can declare the data type of a variable and initialize its contents. The
declaration statements in the following example declare an Integer variable, a Boolean variable,
and an object variable. These are initialized, respectively, to 10, True, and a newly created
instance of the Label class.

Dim Quantity As Integer = 10

Private FirstTry As Boolean = True

Protected MyLabel As New Label

If you do not specify an initialization value for a variable, Visual Basic initializes it to the default
value for its data type. The default initialization values are as follows:

 0 for all numeric types (including Byte).


 Binary 0 for Char.
 Nothing for all reference types (including Object, String, and all arrays).
 False for Boolean.
 12:00 AM of January 1 of the year 1 for Date.

This example uses the Dim statement to declare variables and arrays. The lower bound for array
subscripts is always 0, and the upper bound is the value that appears in the Dim statement.

Dim Number As Integer ' Number is initialized by default to 0.


Dim FirstNumber, SecondNumber, ThirdNumber As Integer
Dim MyDate As Date, MyValue As Single, MySwitch As Boolean

Data Types
The following table shows the Visual Basic .NET data types, their supporting common language runtime
types, their nominal storage allocation, and their value ranges.

Visual Basic Common language Nominal Value range


type runtime type structure storage
allocation

Boolean System.Boolean 2 bytes True or False.

Byte System.Byte 1 byte 0 through 255 (unsigned).

Char System.Char 2 bytes 0 through 65535 (unsigned).

Date System.DateTime 8 bytes 0:00:00 on January 1, 0001 through 11:59:59 PM on


December 31, 9999.

Decimal System.Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335


with no decimal point;
0 through +/-7.9228162514264337593543950335 with
28 places to the right of the decimal; smallest nonzero
number is
+/-0.0000000000000000000000000001 (+/-1E-28).

Double System.Double 8 bytes -1.79769313486231570E+308 through


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

Integer System.Int32 4 bytes -2,147,483,648 through 2,147,483,647.

Long System.Int64 8 bytes -9,223,372,036,854,775,808 through


9,223,372,036,854,775,807.

Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object.

Short System.Int16 2 bytes -32,768 through 32,767.

Single System.Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative


values; 1.401298E-45 through 3.4028235E+38 for
positive values.

String System.String (class) Depends on 0 to approximately 2 billion Unicode characters.


implementing
platform

User-Defined (inherits from Depends on Each member of the structure has a range determined
Type System.ValueType) implementing by its data type and independent of the ranges of the
(structure) platform other members.

Boolean Data Type


Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False. Use the
keywords True and False to assign one of the two states to Boolean variables. When numeric data types
are converted to Boolean values, 0 becomes False and all other values become True.

Byte Data Type


Byte variables are stored as unsigned 8-bit (1-byte) numbers ranging in value from 0 through 255. The
Byte data type is used for containing binary data.The equivalent .NET data type is System.Byte.

Char Data Type


Char variables are stored as unsigned 16-bit (2-byte) numbers ranging in value from 0 through 65535.
Each number represents a single Unicode character. The equivalent .NET data type is System.Char.
Date Data Type
Date variables are stored as 64-bit (8-byte) integers that represent dates ranging from January 1 of the
year 1 through December 31 of the year 9999, and times from 0:00:00 (midnight) through 11:59:59 PM.
Date values must be enclosed within number signs (#) and be in the format m/d/yyyy, for example
#5/31/1993# The equivalent .NET data type is System.DateTime.

Decimal Data Type

Decimal variables are stored as signed 128-bit (16-byte) integers scaled by a variable power of 10. The
scaling factor specifies the number of digits to the right of the decimal point . the D type character to
assign a large value to a Decimal variable or constant, as the following example shows:

Dim BigDec1 As Decimal = 9223372036854775807 ' No overflow.


Dim BigDec2 As Decimal = 9223372036854775808 ' Overflow.
Dim BigDec3 As Decimal = 9223372036854775808D ' No overflow.

Double Data Type


Double variables are stored as signed IEEE 64-bit (8-byte) double-precision
floating-point numbers.

Integer Data Type


Integer variables are stored as signed 32-bit (4-byte) integers ranging in value from -2,147,483,648
through 2,147,483,647. The Integer data type provides optimal performance on a 32-bit processor, as
the smaller integral types are slower to load and store from and to memory.The equivalent .NET data
type is System.Int32.

Long Data Type


Long variables are stored as signed 64-bit (8-byte) integers ranging in value from -
9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.The equivalent .NET data type is
System.Int64.

Object Data Type


Object variables are stored as 32-bit (4-byte) addresses that refer to objects. You can assign any
reference type (string, array, class, or interface) to a variable declared as an Object. An Object variable
can also refer to data of any value type (numeric, Boolean, Char, Date, structure, or enumeration).

Short Data Type


Short variables are stored as signed 16-bit (2-byte) integers ranging in value from -32,768 through
32,767. The equivalent .NET data type is System.Int16.

String Data Type


String variables are stored as sequences of unsigned 16-bit (2-byte) numbers ranging in value from 0
through 65535. Each number represents a single Unicode character. A string can contain up to
approximately 2 billion (2 ^ 31) Unicode characters. The equivalent .NET data type is System.String.
Arrays
An array is a series of variables of the same type (integer, string and so on) When
working with arrays we use an index number to tell the elements of the array a part, Array is
declare like any other variable visua; Basic recognizes both fixed size arrays and variable size
arrays. Fixed size in which the no of elements in the array does not change during execution and
variable size arrays in which the number of elements in the array can change during execution.
syntax:
dim arrayname (size) as type
eg:- dim salary (15) as integer
In this array there are 16 elements in it. By default array start with the index value o. If
we dont specify the starting index no the array is started from zero index value. In this example
the 15 is the upper bound of the array. To store the values in this array we write like this.
salary (o)=1000
salary (1)=2000
By default, the first element of an array has index 0. The number that appears in
parranthesis in the dim statement is the array's upper limit (or upper bound) and is one less than
the array's total capacity. If we want that the first element doesn't need to be 0.
Multidimensional Arrays
One-dimensional arrays are good for storing long sequences of one dimensional data
(such as names and temperatures) In some situation we will want to store sequences of
multidimensional data for example storing a list of cities and their average temperatures in an
array. A two dimensional array has two indices. The first identifies the row, and the second
identifies the column.
dim temp (7,1) as integer
In this syntax the first no indicates the Row and the Second indicates the column. In this example
there are 8 row starting from 0 to 7 and two columns starting from 0 to 1.
To access the name and temperature of the third city in the two dimensional array, we use the
following indexes.
temp (2, 0)
Dynamic Arrays
Sometimes we don't know the size of the array to be built instead of making it large
enough to hold the maximum number of data, we can declare a dynamic array. The size of the
dynamic array can change during the execution of program. To create a dynamic array. Declare
it as usual array with dim statement, but don't specify its dimension.
dim salary () as Single
Later in the program, when we know how many elements we want to store in the array,
we use the Redim statement to redimension the array.
Redim salary (15)
The redim statement can be use only procedure A dynamic array can be redimensioned
to multiple dimensioned. Note that the Redim statement can't change the type of the array. Each
time we execute the Redim statement, all the values currently stored in the array are lost. Visual
Basic resets the values of the elements as if they were just declared. We can also change size of
the array without loosing its data. The Redim statement recognizes the preserve keyword. which
forces it to resize the array without deleting the existing data.
Redim Preserve salary (20)
Introduction to VB.Net Events
Visual Basic .Net is an object-oriented, multi-paradigm based programming language that is
implemented on the .Net framework. This was launched in 2002 by Microsoft which came as a
successor to the most popular Visual Basic language. The IDE or the integrated development
environment provided by Microsoft for tackling and handling this Visual basic language is
Microsoft Visual Studio. The visual studio express and the community version are the non-paid
unlicensed versions of the tool which therefore forms the part of the freeware. The freeware
includes a command-line compiler SDK which is called the vbc.exe. Mono also makes use of the
command line VB .NET compiler. One of the very prime features of the visual basic language is
that it makes use of the statements which is used to specify actions. In this article, we will
discuss about VB.Net Events in detail.
Types of VB.Net Events
Below are the Two types of VB. Net event:
1. Mouse-Based Events
Mouse events occur when the mouse makes any movement in controls or the forms. The
following are some of the mouse-related events which are related to a control class.
i. MouseEnter
This event gets triggered when the pointer of the mouse enters the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseEnter
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseEnter(sender As ObjectType, e As EventArguments)
Handles abc.MouseEnter
//writes the code for handling mouse enter on abc textbox
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
ii. MouseDown
This event gets triggered when the mouse button is pressed and the cursor is brought towards the
downside of it.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseDown
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseDown(sender As ObjectType, e As EventArguments)
Handles abc.MouseDown
//writes the code for handling mouse down
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
iii. MouseUp
This event gets triggered when the mouse pointer is over the control which is handling it and the
already pressed mouse button is released.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseUp
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseUp(sender As ObjectType, e As EventArguments)
Handles abc.MouseUp
//writes the code for handling mouseUp
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
iv. MouseLeave
This is the event that gets triggered when the mouse pointer leaves the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseLeave
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseLeave(sender As ObjectType, e As EventArguments)
Handles abc.MouseLeave
//writes the code for handling mouseLeave for abc textbox
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
v. MouseWheel
This event gets triggered when the wheel of the mouse moves and the control is provided the
focus.
Syntax
<element onwheel="mytestScript">
object.onwheel = function(){mytestScript};
object.addEventListener("wheel", mytestScript);
Example:
document.getElementById("DIV").addEventListener("wheel", testFunction);
function testFunction() {
this.style.fontSize = "70px";
}
2. Keyboard Based Events
These are the events that are triggered when the events are fired upon any action done on the
keyboard. This includes actions such as keypress, keydown, enter, etc. Let us study some of the
keyboard-based events in detail.
i. KeyDown
This event is a keyboard-based trigger that occurs when a key is pressed towards the downside
and the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.KeyDown
Program Body
End Sub
Example:
Private Sub KeyDown(sender As Object, e As KeyEventArgs) _
Handles abc.KeyDown
If (KeyDown.IsNumber(Chr(e.KeyCode))) Then
alert.Show("Enter Customer ID number")
abc.Text = " "
End If
End Sub
ii. KeyUp
This event is a keyboard-based trigger that occurs when a key is pressed towards the upside and
the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.KeyUp
Program Body
End Sub
Example:
Private Sub KeyUp(sender As Object, e As KeyEventArgs) _
Handles abc.KeyUp
If (KeyUp.IsNumber(Chr(e.KeyCode))) Then
alert.Show("Enter Customer ID number")
abc.Text = " "
End If
End Sub
iii. KeyPress
This event gets triggered when a particular key is pressed onto the keyboard.
Syntax:
Public Class class_name
private sub func_name(alias as Datatype1, alias as KeyPressArguments)
Handles object.KeyPress
Program Body
End Sub
Example:
Public Class testKeyPress
Private Sub KeyPress(Value sender As System.Object, Value e As
System.Windows.KeyPressEventArguments) Handles abc1.KeyPress
If !(e.KeyChar = Convert.ToChar(10)) Then
MsgBox("key is not pressed ")
End If
End Sub
End Class

Text Box Control


Windows Forms text boxes are used to get input from the user or to display text. The
TextBox control is generally used for editable text, although it can also be made read-only. Text
boxes can display multiple lines, wrap text to the size of the control, and add basic formatting.
The text displayed by the control is contained in the Text property. By default, you can
enter up to 2048 characters in a text box. If you set the MultiLine property to true, you can
enter up to 32 KB of text. The Text property can be set at design time with the Properties
window, at run time in code, or by user input at run time...
The code below sets text in the control at run time. The InitializeMyControl
procedure will not execute automatically; it must be called.
TextBox1.Text = "This is a TextBox control."
Basic Properties.
1. MultiLine Property:- true if the control is a multiline text box
control; otherwise, false. A multiline text box allows you to display
more than one line of text in the control.
textBox1.Multiline = True
2. MaxLength:- The number of characters that can be entered into the control. The
default is zero.
textBox1.MaxLength = 8
3. Enabled :- true if the control can respond to user interaction; otherwise, false. The default is
true.
Textbox1.enabled=true
4. Password Char=to convert a standard text box into a password box, you just assign some
character to the text box.
textBox1.PasswordChar = "*"
5. Scroll Bar. If user’s are going to be entering a lot of text into text boxes. we are using scroll
bar property
6. Backcolor=A Color that represents the background of the control.
7. Text=the text associated with this control.
8. Visible =true if the control is displayed; otherwise, false. The default is true.
9. Tab Index =the index value of the control within the set of controls within its container that
are included in the tab order.
Public Methods
1.Copy Methods -> You can use this method, instead of using the Clipboard class, to copy text in
the text box and place it in the Clipboard.

textBox1.Copy()
2. Cut-> This method will only cut text from the text box if text is
selected in the control. You can use this method, instead of using the
Clipboard class, to copy text in the text box and move it to the
Clipboard.

3. Paste -> The Paste method will only paste text into the control if text is currently
stored in the Clipboard. Once your application exits, any content stored in the Clipboard
is removed.

4. Hide -> Hiding the control is equivalent to setting the Visible property to false. After
the Hide method is called, the Visible property returns a value of false until the Show
method is called.

5. Clear->You can use this method to clear the contents of the control instead of assigning the
Text property an empty string.

Public Events:-

BackColorChanged=This event is raised if the BackColor property is changed by either a programmatic


modification or user interaction.

Click Occurs when the text box is clicked.

DoubleClick Occurs when the control is double-clicked.

Keypress Occurs when a key is pressed while the control has focus.

TextChanged Occurs when the Text property value changes.

Leave Occurs when the input focus leaves the control.

ForeColorChanged Occurs when the ForeColor property value changes.

Text Selection, Search operation ,Replace operation :


Controlling the Insertion Point in a Windows Forms TextBox Control

When a Windows Forms TextBox control first receives the focus, the default insertion within the
text box is to the left of any existing text. The user can move the insertion point with the
keyboard or the mouse. If the text box loses and then regains the focus, the insertion point will be
wherever the user last placed it.

In some cases, this behavior can be disconcerting to the user. In a word processing application, the user
might expect new characters to appear after any existing text. In a data entry application, the user might
expect new characters to replace any existing entry. The SelectionStart and SelectionLength properties
allow you to modify the behavior to suit your purpose.

Some Important properties

To control the insertion point in a TextBox control

1. Set the SelectionStart property to an appropriate value. Zero places the insertion point
immediately to the left of the first character.
2. (Optional) Set the SelectionLength property to the length of the text you want to select.

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


System.EventArgs) Handles TextBox1.Enter
TextBox1.SelectionStart = 0
TextBox1.SelectionLength = 5
End Sub
Code to Validate User Input
We can make sure that a TextBox can accept only characters or numbers, which can restrict accidental
operations. For example, adding two numbers of the form 27+2J cannot return anything. To avoid such
kind of operations we use the KeyPress event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this:

Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As _


System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub
Creating a TextBox in Code

Public Class Form1 Inherits System.Windows.Forms.Form


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim TextBox1 as New TextBox()
TextBox1.Text="Hello Mate"
TextBox1.Location=New Point(100,50)
TextBox1.Size=New Size(75,23)
Me.Controls.Add(TextBox1)
End Sub
End Class

List Box Control


The ListBox control enables you to display a list of items to the user that the user can select by clicking.
A ListBox control can provide single or multiple selections using the Selection Mode property. The
ListBox also provides the Multicolumn property to enable the display of items in columns instead of a
straight vertical list of items. This allows the control to display more visible items and prevents the need
for the user to scroll to an item.

The Items, Selected Items, and Selected Indices properties provide access to the three collections that
are used by the ListBox. The following table outlines the three collections used by the ListBox and their
use within the control.

Basic Public Properties.

1. SelectedIndex : Gets or sets the zero-based index of the currently selected item in a List
Box. A value of negative one (-1) is returned if no item is selected.
2. Items : A ListBox.ObjectCollection representing the items in the List Box. This property enables
you to obtain a reference to the list of items that are currently stored in the ListBox.
3. SelectedItem : An object that represents the current selection in the control. For a standard
ListBox, you can use this property to determine which item is selected in the ListBox. If the
SelectionMode property of the ListBox is set to either SelectionMode.MultiSimple or
SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items
are selected in the list, this property can return any selected item.
4. Selected Indices : A ListBox.SelectedIndexCollection containing the indexes of the currently
selected items in the control. If no items are currently selected, an empty
ListBox.SelectedIndexCollection is returned.For a multiple-selection ListBox, this property returns
a collection containing the indexes to all items that are selected in the ListBox. For a single-
selection ListBox, this property returns a collection containing a single element containing the
index of the only selected item in the ListBox. For more information on how to manipulate the
items of the collection, see ListBox.SelectedIndexCollection.
5. MultiColumn: true if the list box supports multiple columns; otherwise, false. The default is false.
A multicolumn list box places items into as many columns as are needed to make vertical scrolling
unnecessary.
6. SelectionMode : The SelectionMode property enables you to determine how many items in the
List Box a user can select at one time and how the user can make multiple-selections. When the
SelectionMode property is set to SelectionMode.MultiExtended, pressing SHIFT and clicking the
mouse or pressing SHIFT and one of the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW,
and RIGHT ARROW) extends the selection from the previously selected item to the current item.
Pressing CTRL and clicking the mouse selects or deselects an item in the list. When the property is
set to SelectionMode.MultiSimple, a mouse click or pressing the SPACEBAR selects or deselects
an item in the list.
7. Count : Gets the number of items in the collection.
8. Item : Property Value An object representing the item located at the specified index within the
collection.
9. Sorted : Windows Forms controls do not sort when they are data-bound. To display sorted data,
use a data source that supports sorting and then have the data source sort it. If the control is not
data-bound, then setting the Sorted property to true repositions all existing list items in sorted
order.
Public Methods
1. ClearSelected : Calling this method is equivalent to setting the Selected Index
property to negative one (-1). You can use this method to quickly remove unselect all
items in the list.
2. Dispose = Releases the resources used by the Component

3. Add.Item : Adding Items from a ListBox Control Items can be added to a Windows Forms list
box in a variety of ways, since these controls can be bound to a variety of data sources.

ComboBox1.Items.Add ("Tokyo")

Insert the string or object at the desired point in the list with the Insert method:

CheckedListBox1.Items.Insert (3, "Copenhagen")

4. To remove an item

Call the Remove or RemoveAt method to delete items.

Remove has one argument that specifies the item to remove. RemoveAt removes the
item with the specified index number.

' To remove item with index 0:


listbox1.Items.RemoveAt (0)
' To remove currently selected item:
ListBox1.Items.Remove (ComboBox1.SelectedItem)
' To remove "Tokyo" item:
ListBox1.Items.Remove ("Tokyo")

5. List. Clear : When you remove items from the list, all information about the deleted items is
lost. To remove a single item from the List Box, use the Remove or Remove At method.

Common Events

1. SelectedIndexChanged= you can create an event handler for this event to determine when the
selected index in the List Box has been changed. This can be useful when you need to display
information in other controls based on the current selection in the ListBox.
2. DoubleClick Event =Occurs when the control is double-clicked.
3. Enter= Occurs when the control is entered.
4. Leave Occurs when the input focus leaves the control.
5. Keypress= Occurs when a key is pressed while the control has focus
6. Working with ListBoxes :

Code to display the index of an item

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


Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedIndex
End Sub
Counting the number of Items in a ListBox

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


Handles Button1.Click
TextBox1.Text = ListBox1.Items.Count
End Sub

Code to display the item selected from ListBox in a TextBox

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedItem
End Sub

Code to Remove items from a ListBox

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


Handles Button1.Click
ListBox1.Items.RemoveAt(4)
End Sub

Code to Remove all items


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
End Sub

Combo Box control


The Windows Forms ComboBox control is used to display data in a drop-down combo box. By
default, the ComboBox control appears in two parts: the top part is a text box that allows the
user to type a list item. The second part is a list box that displays a list of items from which the
user can select one..

The SelectedIndex property returns an integer value that corresponds to the selected list item.
You can programmatically change the selected item by changing the SelectedIndex value in
code; the corresponding item in the list will appear in the text box portion of the combo box. If
no item is selected, the SelectedIndex value is -1. If the first item in the list is selected, then the
SelectedIndex value is 0. The SelectedItem property is similar to SelectedIndex, but returns the
item itself, usually a string value. The Items.Count property reflects the number of items in the
list, and the value of the Items.Count property is always one more than the largest possible
SelectedIndex value because SelectedIndex is zero-based.

To add or delete items in a ListBox control, use the Items.Add, Items.Insert, Items.Clear or
Items.Remove method. Alternatively, you can add items to the list by using the Items property in the
designer.
Properties
1. Items Gets an object representing the collection of the items contained in this Combo Box

This property enables you to obtain a reference to the list of items that are currently stored in
the Combo Box. With this reference, you can add items, remove items, and obtain a count of the
items in the collection.

Example

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

comboBox1.Items.Add (textBox1.Text)
End Sub
2 SelectedItem : An object that represents the current selection in the control. For a standard List
Box, you can use this property to determine which item is selected in the ListBox. If the
Selection Mode property of the ListBox is set to either SelectionMode.MultiSimple or
SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items
are selected in the list, this property can return any selected item.
3. SelectedIndex : Gets or sets the zero-based index of the currently selected item in a List Box. A
value of negative one (-1) is returned if no item is selected.
4. Sorted : Windows Forms controls do not sort when they are data-bound. To display sorted data,
use a data source that supports sorting and then have the data source sort it. If the control is
not data-bound, then setting the Sorted property to true repositions all existing list items in
sorted order.

When to Use a Windows Forms ComboBox Instead of a ListBox


The ComboBox and the ListBox controls have similar behaviors, and in some cases may be
interchangeable. There are times, however, when one or the other is more appropriate to a task.

Generally, a combo box is appropriate when there is a list of suggested choices, and a list box is
appropriate when you want to limit input to what is on the list. A combo box contains a text box
field, so choices not on the list can be typed in. The exception is when the DropDownStyle
property is set to ComboBoxStyle.DropDownList. In that case, the control will select an item if
you type its first letter.

In addition, combo boxes save space on a form. Because the full list is not displayed until the
user clicks the down arrow, a combo box can easily fit in a small space where a list box would
not fit. An exception is when the DropDownStyle property is set to ComboBoxStyle.Simple:
the full list is displayed, and the combo box takes up more room than a list box would.
The Label
The Label as name implies a sticker on that some thing can be written. The
same is with this control. This is used to give a description to the control to
which it is described. It in most cases come with a combination. Like when you
create a check box it accompanies a label. Label controls also prompt you to
perform an action though in rare cases. The caption for a label is stored in the
Text property. Because you can change that caption in code, labels can act a
little like no editable text boxes, displaying text and messages to the user. The
Text Align ((formerly Alignment) property allows you to set the alignment of
the text within the label.

The Chekbox
The checkbox is a control that you may use to select one more choices among
many. You can select all even. You click a checkbox to select it, and click it
again to deselect it. When you select a checkbox, a check appears in it,
indicating that the box is indeed selected. You use a checkbox to give the user
an option, such as true/false or yes/no. The checkbox control supports two or
three states. For standard checkboxes, you use the checked property to get or
set the value of a checkbox control, but for three-state checkboxes, which
support an “indeterminate” state, you use the Check state property. The
indeterminate state is sort of a middle state between checked and unchecked.

The most common properties the control has are as follows:


Property Means
Appearance Gets/sets the appearance of a checkbox.

Auto Check Specifies if the Checked or Check state values and the checkbox’s appearance are
automatically changed when the checkbox is clicked.
Check Align Gets/sets the horizontal and vertical alignment of a checkbox in a checkbox control.

Checked Gets/sets a value indicating if the checkbox is in the checked state.

Check state Gets/sets the state of a three-state checkbox.

Flat style Gets/sets the flat style appearance of the checkbox.

Image Gets/sets the image that is displayed in a checkbox.

Image Align Gets/sets the alignment of the image on the checkbox.

Image Index Gets/sets the image list index value of the image displayed in the checkbox.

Image List Gets/sets the Image List that contains the image displayed in a checkbox.

The Radio Buttons


Radio buttons, also called option buttons, are similar to checkboxes-the user can select and
deselect them-except for two things: they are round where checkboxes are square, and you
usually use radio buttons together in groups also checkboxes can work independently, but
radio buttons are intended to work in groups. When the user selects one radio button in a
group, the others clear automatically. All radio buttons in a given container, such as a form,
make up a group. To create multiple groups on one form, you place each additional groups
in its own container, such as a group box or panel control.

Important properties of Radio Buttons are:

Property Means
Appearance Gets/sets the value that determines the appearance of the radio
button.

AutoCheck Gets/sets a value indicating whether the Checked value and the
appearance of the/ control automatically change when the radio
button is clicked.

Checked Gets/sets a balue indicating whether the radio button is checked.


FlatStyle Gets/sets the flat style appearance of the radio button.

Image Gets/sets the image that is displayed in a radio button.

Image Align Gets/sets the alignment of the image in a radio button.

ImageIndex Gets/sets the image list index value of the image displayed in a
radio button.

ImageList Gets/sets the ImageList that contains the image displayed in a


radio button.

TextAlign Gets/sets the alignment of the text in a radio button.

Here’s an example showing how to determine whether a radio button is selected or not.
In this case, we display a message in a message box that indicates if a radio button,
RadioButton1, is selected or not:

Private Sub Button1_Click (Byva1 sender As System.Object, Byva1e As System. Event Args)
Hand1es

Button1. Click

If RadioButton1. Checked Then

MsgBox (“The Radio Button is checked”)

Else

MsgBox (“The Radio Button is unchecked.”)

End If

End Sub

Tree view control:


If you need to show hierarchical data in a tree like format in VB NET, you should use the
tree view control. This flexible control allows you to change numerous properties in order to fit
your needs each node is not only displayed visually, but also can have child nodes, an example
of this is the windows explorer, which uses a tree view in its left pane to display the hierarchy of
folders on disk. You can expand and collapse parent nodes by clicking them; when expanded,
their children are also visible the tree view control also lets you add nodes and sub nodes, in
design time, but you will usually to this in run time. To add the tree view control to your form,
open the toolbox find the tree view control under the common controls section, and double
click it

Important properties of tree view objects.

Property Means
Border style Gets/sets the tree view’s border style.

Check boxes Gets/ sets whether checkboxes should be displayed next to tree
nodes

Image index Gets/sets the image list index of the current image.

Image list Gets/ sets the image list used with this tree view.

Label edit Gets/sets whether tree node next can be edited.

Nodes Gets the collection of tree nodes.

Path separator Gets/ sets the string the tree node uses as a path delimiter.

Scrollable Gets/sets whether the tree view should display scroll bars as needed.

Selectedimage index Gets/sets the image index for the image to display when a node is
selected.

Selected node Gets/sets the node that is selected.


Events of tree view objects.

Event means
After check Occurs when a node check box is checked.

After collapse Occurs when a tree node is collapsed.

After expand Occurs when a tree node is expanded

After label edit Occurs when a tree node label text is edited.

After select Occurs when a tree node is selected.

Before check Occurs before a node check box is checked.

Before collapse Occurs before a node is collapsed.

Before expand Occurs before a node is expanded.

Before label edit Occurs before a node label text is edited.

Before select Occurs before a node is selected.

Item drag Occurs when an item is dragged into the tree view.

Toolbar control:
Toolbars are seen in almost every application, and gives users quick access to regularly
used features such as save. Microsoft offers a toolbar control in its common controls, which
makes it very easy to add a toolbar to your own application. To add a toolbar to the top of your
form, expand the toolbox and locate the toolbar control (you may have to scroll down to see it)
double click the toolbar control, and it will be added to the top of your form. However, there’s
not much to see, at the moment, toolbars work by adding buttons and images to them. The
button is that clicked, and an action performed. Click on your Toolbar to select it. In the
property box for the Toolbar, you’ll notice that it has the default Name of ToolBarl. We’ll keep
this Name. But locate the Buttons (Collection) property, and click the button with the three
dots in it. This brings up the toolBarButton Collection Editor. To add a new button to your
toolbar, click the add button:

Each button on the toolbar has it’s own properties and methods. The button you have
just added has a default Name of ToolBarButtonl. This is not terribly descriptive. What we’re
giving to do is add three toolbar buttons: one to create a new file, one to open a file, and one to
save a file. So,
Click the Name property and change it to tbrFileNew

Click Add to create a second button

Change the Name of this to tbrfile Open

Add a their button and change the Name property to tbrFileSave

Then click OK

LinkLabel Class:
The LinkLabel control is similar to a Label control with the exception that is can display a
hyperlink. Multiple hyperlinks can be specified in the text of the control. Each hyperlink can
perform a different task within a application, For example, you can use a hyperlink to display a
Web site in Microsoft Internet Explorer or to load a log file associated with an application.

Each hyperlink displayed in the Linklabel control is an instance of the LinkLabel Link
class. The linklabel. Link class defines display information, state, and location of the hyoperlink.
In addition, the Linkata property of the LinkLabel. Link class enables you to associate
information, such as a URL, to display, with the hyperlink. When a user clicks a hyperlink within
the control, the LinkClicked event is raised, and the LinkLabel. Link object representing the
hyperlink that was clicked is passed as part of the LinkLabelLink Clicked Event Args object that is
passed as a parameter to the event handler. You can use this object to obtain the LinkLabel.
Link object associated with the hyperlink that was clicked by the user. All hyperlink contained
within the LinkLabel control are stored in the LinkLabel. Link Collection class instance for the
control.

There are two ways to add a hyperlink to the Link Label control. The quickest way is to
specify a LinkArea and assign it to the Link Area property. This enables you to specify a single
hyperlink within the text of the control. To add multiple hyperlinks, you can use the Add
method of the LinkLabel.Link Collection class by accessing the collecton through the Links
property.

When a LinkLabel control, a default hyperlik that contains all the text within the
LinkLabel control is added to the LinkLabel. Link Collection. You can override this default link by
specifying a new link area with the Link Aera property, or specify a link using the Addmethod of
the LinkLabel. Link Collection. You can also remove the default hyperlink by using the remove
method of the LinkLabel. Link Collectionclass.

The linkLabel provides a number of properties that enable you to define the display
appearance of hyperlinks in the control. The Active Link Color, Disabled LinkColor, Link Color,
and Visited Link Color properties define the colors used when displaying a hyperlink in various
states. The link Behavior property defines the display of the underline that is associated with a
hyperlink.

Common Dialogs

Visual Basic .NET comes with built-in dialog boxes which allow us to create our own
File Open, File Save, Font, Color dialogs much like what we see in all other windows
applications. To make a dialog box visible at run time we use the dialog box's ShowDialog
method. The Dialog Boxes which come with Visual Basic .NET are: OpenFileDialog,
SaveFileDialog, FontDialog, ColorDialog, PrintDialog, PrintPreviewDialog and
PageSetupDialog. We will be working with OpenFile, SaveFile, Font and Color Dialog's in this
section. The return values of all the above said dialog boxes which will determine
which selection a user makes are: Abort, Cancel, Ignore, No, None, OK, Return, Retry and
Yes.
1.Open file dialog box 2.Save file dialog Box 3.Font dialog box

4. Color Dialog Box 5.Print dialog box

1. Open File Dialog Box

The Windows Forms OpenFileDialog component is a pre-configured dialog box. It is the same
Open File dialog box exposed by the Windows operating system. It inherits from the
CommonDialog class.

The general concepts of the OpenFileDialog component, which allows you to display a pre-
configured dialog box that users can use to open files. Use this component within your Windows
application as a simple solution for file selection in lieu of configuring your own dialog box. By
relying on standard Windows dialog boxes, you create applications whose basic functionality is
immediately familiar to users

Use the ShowDialog method to display the dialog at run time. You can enable users to multi-
select files to be opened with the Multiselect property. Additionally, you can use the
ShowReadOnly property to determine if a read-only check box appears in the dialog box. The
ReadOnlyChecked property indicates whether the read-only check box is selected. Finally, the
Filter property sets the current file name filter string, which determines the choices that appear in
the "Files of type" box in the dialog box.
Some Basic Properties
1. AddExtension = Gets or sets a value indicating whether the dialog box automatically adds an
extension to a file name if the user omits the extension.

AddExtension As Boolean

2. DefaultExt= The default file name extension. The returned string does not include the period (.). The
default value is an empty string("").

DefaultExt As String

3. FileName = Gets or sets a string containing the file name selected in the file dialog box. A string
containing the file name selected in the file dialog box. The default value is an empty string ("").

FileName As String

4. FileNames Gets the file names of all selected files in the dialog box. An array of values containing the
file names of all selected files in the dialog box.

FileNames As String ()
5.Filter Property Gets or sets the current file name filter string, which determines the
choices that appear in the "Save as file type" or "Files of type" box in the dialog box.
Filter As String

A string that contains information about the file filtering options available in the dialog box.

For each filtering option, the filter string contains a description of the filter, followed by the vertical bar
(|) and the filter pattern. The strings for different filtering options are separated by the vertical bar.
The following is an example of a filter string: "Text files (*.txt)|*.txt|All files (*.*)|*.*"

You can add serveral filter patterns to a filter by separating the file types with smicolons. For example:
"Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"

6. FilterIndex Property. Gets or sets the index of the filter currently selected in the file dialog box.

FilterIndex As Integer

A value containing the index of the filter currently selected in the file dialog box. The first filter is at
index one. The default value is one.

7. Initial Directory Property. Gets or sets the initial directory displayed by the file dialog box.

InitialDirectory As String

A string containing the initial directory displayed by the file dialog box. The default is an empty string
("").

8. Multiselect Property . True if the dialog box allows multiple files to be selected together or
concurrently; otherwise, false. The default value is false.

Multiselect As Boolean

9. ShowHelp . Gets or sets a value indicating whether the Help button is displayed in the file dialog.

ShowHelp As Boolean

10. Title Property . A string containing the file dialog box title. The default value is an empty string ("").

Title As String

Common Methods

1. OpenFile Method . The OpenFile method is used to provide a facility to quickly open a
file from the dialog box. The file is opened in read-only mode for security purposes.
2. ShowDialog Method. Runs a common dialog box with a default owner.
DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel

3. Reset Method Resets all properties to their default values.

Common Events

1. FileOk Event . Occurs when the user clicks on the Open or Save button on a file dialog box.

2. HelpRequest Event Occurs when the user clicks the Help button on a common dialog box.
2. SaveFileDialog Component
The Windows Forms SaveFileDialog component is a pre-configured dialog box. It is the same as
the standard Save File dialog box used by Windows. It inherits from the CommonDialog class.

Use it as a simple solution for enabling users to save files in lieu of configuring your own dialog
box. By relying on standard Windows dialog boxes, the basic functionality of applications you
create is immediately familiar to users. You can use the ShowDialog method to display the
dialog box at run time. You can open a file in read-write mode using the OpenFile method.
When it is added to a form, the SaveFileDialog component appears in the tray at the bottom of
the Windows Forms Designer.

Some Basic Properties


1. AddExtension = Gets or sets a value indicating whether the dialog box automatically adds an
extension to a file name if the user omits the extension.
AddExtension As Boolean
2. DefaultExt= The default file name extension. The returned string does not include the period (.). The
default value is an empty string("").
DefaultExt As String
3. FileName = Gets or sets a string containing the file name selected in the file dialog box. A string
containing the file name selected in the file dialog box. The default value is an empty string ("").
FileName As String
4. FileNames Gets the file names of all selected files in the dialog box. An array of values containing the
file names of all selected files in the dialog box.
FileNames As String ()
5.Filter Property Gets or sets the current file name filter string, which determines the choices that
appear in the "Save as file type" or "Files of type" box in the dialog box.
Filter As StringA string that contains information about the file filtering options available in the dialog
box. For each filtering option, the filter string contains a description of the filter, followed by the vertical
bar (|) and the filter pattern. The strings for different filtering options are separated by the vertical bar.
The following is an example of a filter string: "Text files (*.txt)|*.txt|All files (*.*)|*.*"
You can add serveral filter patterns to a filter by separating the file types with smicolons. For example:
"Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"
6. FilterIndex Property. Gets or sets the index of the filter currently selected in the file dialog box.
FilterIndex As Integer
A value containing the index of the filter currently selected in the file dialog box. The first filter is at
index one. The default value is one.
7. Initial Directory Property. Gets or sets the initial directory displayed by the file dialog box.
InitialDirectory As String
A string containing the initial directory displayed by the file dialog box. The default is an empty string
("").
8. Multiselect Property . True if the dialog box allows multiple files to be selected together or
concurrently; otherwise, false. The default value is false.
Multiselect As Boolean
9. ShowHelp . Gets or sets a value indicating whether the Help button is displayed in the file dialog.
ShowHelp As Boolean
10. Title Property . A string containing the file dialog box title. The default value is an empty string ("").
Title As String

Common Methods
1. OpenFile Method . The OpenFile method is used to provide a facility to quickly open a file from
the dialog box. The file is opened in read-only mode for security purposes.
2. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK if the
user clicks OK in the dialog box; otherwise, DialogResult.Cancel .
3. Reset Method Resets all properties to their default values.
Common Events

1. FileOk Event . Occurs when the user clicks on the Open or Save button on a file dialog
box.
2. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.

3. Font Dialog Box


The Windows Forms FontDialog component is a pre-configured dialog box, which is the standard
Windows "Font" dialog box used to expose the fonts that are currently installed on the system. Use it
within your Windows application as a simple solution for font selection in lieu of configuring your own
dialog box.

By default, the dialog box shows list boxes for Font, Font style, and Size; check boxes for effects
like Strikeout and Underline; a drop-down list for Script; and a sample of how the font will
appear. (Script refers to different character scripts that are available for a given font, for example
Hebrew or Japanese.) To display the font dialog box, call the ShowDialog method.

The component has a number of properties that configure its appearance. The properties that set
the dialog-box selections are Font and Color. The Font property sets the font, style, size, script,
and effects; for example, Arial, 10pt, style=Italic, Strikeout.

Basic Property

1. Color Property Gets or sets the selected font color. The color of the selected font. The
default value is Black.

2. Font property. Gets or sets the selected font.

3. MaxSize Property . Gets or sets the maximum point size a user can select.

The maximum point size a user can select. The default is zero.In order for the maximum and
minimum size settings to take effect, MaxSize must be greater than MinSize, and both must be
greater than zero.

4. MinSize Property. Gets or sets the minimum point size a user can select. The minimum point size a
user can select.

5. ShowApply Property . Gets or sets a value indicating whether the dialog box contains an Apply
button. True if the dialog box contains an Apply button; otherwise, false. The default value is
false.

6.ShowColor Property Gets or sets a value indicating whether the dialog box displays the
color choice.True if the dialog box displays the color choice; otherwise, false. The default value
is false.

7. Show Effects Sets a value indicating whether the dialog box contains controls that allow the
user to specify strikethrough, underline, and text color options.

8. Show Apply. Sets a value indicating whether the dialog box contains an Apply button.

9. Show Help. Sets a value indicating whether the dialog box displays a Help button.

Common Methods

1. ShowDialog Method. Runs a common dialog box with a default owner.


DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel
.
2. Reset Method resets all properties to their default values.
Common Events

3. Apply Event . Occurs when the user clicks the Apply button in the font dialog box.
4. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.

4. Color Dialog Box


The Windows Forms ColorDialog component is a pre-configured dialog box that allows the user
to select a color from a palette and to add custom colors to that palette. It is the same dialog box that
you see in other Windows applications to select colors. The color selected in the dialog box is returned
in the Color property. If the AllowFullOpen property is set to false, the "Define Custom Colors" button is
disabled and the user is restricted to the predefined colors in the palette. If the SolidColorOnly property
is set to true, the user cannot select dithered colors. To display the dialog box, you must call its
ShowDialog method.

Basic Properties
1. Allow Full Open Gets or sets a value indicating whether the user can use the dialog box to define
custom colors.
2. Any Color Gets or sets a value indicating whether the dialog box displays all available colors in the set
of basic colors.
3. Color Gets or sets the color selected by the user.
4.CustomColors Gets or sets the set of custom colors shown in the dialog box.
5. Full Open Gets or sets a value indicating whether the controls used to create custom colors are visible
when the dialog box is opened
6. Show Help Gets or sets a value indicating whether a Help button appears in the color dialog box.
7.SolidColorOnly . Gets or sets a value indicating whether the dialog box will restrict users to selecting
solid colors only.
Common Methods
1. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK
if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel .
2. Reset Method resets all properties to their default values.
Common Events
1. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.

5. Print Dialog Control. The Windows Forms Print Dialog component is a pre-configured
dialog box used to select a printer, choose the pages to print, and determine other print-related
settings in Windows applications. Use it as a simple solution for printer and print-related settings
selection in lieu of configuring your own dialog box. You can enable users to print many parts of
their documents: print all, print a specified page range, or print a selection. By relying on
standard Windows dialog boxes, you create applications whose basic functionality is
immediately familiar to users
Basic Properties

1. Allow PrintToFile Gets or sets a value indicating whether the Print to file check box is
enabled.
2. AllowSelection Gets or sets a value indicating whether the From... To... Page option
button is enabled.
3. AllowSomePages Gets or sets a value indicating whether the Pages option button is
enabled.\
4. Document Gets or sets a value indicating the PrintDocument used to obtain
PrinterSettings.
5. PrinterSettings Gets or sets the PrinterSettings the dialog box modifies.
6. PrintToFile Gets or sets a value indicating whether the Print to file check box is checked.
7. ShowHelp Gets or sets a value indicating whether the Help button is displayed.
8. ShowNetwork Gets or sets a value indicating whether the Network button is displayed.
Common Methods
1. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK if the
user clicks OK in the dialog box; otherwise, DialogResult.Cancel .

2. Reset Method resets all properties to their default values.

Common Events

2. HelpRequest Event Occurs when the user clicks the Help button on a
common dialog box.

Example:
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
RichTextBox1.Text = " "
End Sub

Private FileName As String


Dim sr As StreamReader
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MenuItem2.Click
Try
With OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
sr = New StreamReader(.OpenFile)
RichTextBox1.Text = sr.ReadToEnd()
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
Finally
If Not (sr Is Nothing) Then
sr.Close()
End If
End Try
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles MenuItem3.Click
Dim sw As StreamWriter
Try
With SaveFileDialog1
.FileName = FileName
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
sw = New StreamWriter(FileName)
sw.Write(RichTextBox1.Text)
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
Finally
If Not (sw Is Nothing) Then
sw.Close()
End If
End Try
End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles MenuItem4.Click
Try
With FontDialog1
.Font = RichTextBox1.Font
.Color = RichTextBox1.ForeColor
If .ShowDialog = DialogResult.OK Then
setFont()
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub setFont()


Try
With FontDialog1
RichTextBox1.Font = .Font
If .ShowColor Then
RichTextBox1.ForeColor = .Color
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub MenuItem5_Click(ByVal sender As System.Object, ByVal e As _


System.EventArgs) Handles MenuItem5.Click
Static CustomColors() As Integer = {RGB(255, 0, 0), RGB(0, 255, 0), RGB(0, 0, 255)}
Try
With ColorDialog1
.Color = RichTextBox1.ForeColor
.CustomColors = CustomColors
If .ShowDialog() = DialogResult.OK Then
RichTextBox1.ForeColor = .Color
CustomColors = .CustomColors
End If
ColorDialog1.Reset()
End With
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub
End Class

Modal and Modeless Form


A modal from is one that has to be dealt with before a user can continue. An
example is the Change Case dialogue box in Microsoft Word. If you try to click
away from the dialogue box, you'll here a beep to indicate an error. Until you
click either the Cancel or OK buttons, the programme won't let you click
anywhere else.

The second form you've just created is called a Modeless form. These are
forms than can be hidden or sent to the taskbar. You can then return to the
main form or programme and do things with it.

A Modal form is sometimes called a dialogue box. And we'll see how to create
one of these now.

Add a second button to your Form1. Change the Name property of the new
button to btnDialogueBox. Double click the new button and add the following
code:

Dim frmDialogue As New frmSecond

frmDialogue.ShowDialog()

To display a form as a Modal dialogue box, you use the ShowDialog method.
If you use the Show method, the form is displayed as a Modeless form.
Run your programme. Click your new button, and the second form should
display. Move it out the way and try to click a button on Form1. You won't be
able to. The second form has to be dealt with before you can access Form1.

When the form is a Modal dialogue box, you can create OK and Cancel
buttons for it. VB.NET then has a trick up its sleeve for these types of buttons.
We'll see that trick now.

After defining the structure of your form with the WinForms designer you
can display your forms in code with two different methods.

 Method - A Modeless form


Form1 aForm1Instance = new Form1();
aForm1Instance.Show();

 Method - A Modal Dialog


Form2 aForm2Instance = new Form2();
aForm2Instance.ShowDialog();
The two methods have a very important distinction. The first method (the
modeless one) shows your form and then returns immediately without waiting
the closure of the just opened form. So your code continues with whatever
follows the Show call. The second method instead (the modal one) opens the
form and blocks any activity on the whole application until you close the form
via the close button or with some buttons appropriately configured to close the
form

Menus
Every windows user is familiar with menus you wouldn’t get far in
windows without them. Menu are those controls that allow the user to make
selections and also hide away those selection when they are not needed
saving space in windows applications.

Menu items
Menu like file or edit and the actual items in such menus or supported with the
menus items class. This class supports the actual control in your menus systems , and
its their click event that you code to in order to make that menu system active.
You can use the shortcut properties to define a keyboard combination(like
Ctrl+X) that can be pressed to select the menu item ,set the show shortcut property to
true to display that key combination in the menu items caption. To set the caption of a
menu items you use the text property . setting the text to a hyphen(-) converts the menu
items into a menu separator, one of those horizontal bars that help group together. You
can even have separator in mean the bars , In & underlines that character and makes it
into an access key, which mean the use the user can select that item by pressing alt
and that character. For example giving a menu items the caption “E&xit” makes x in to
the access key for these menu items .you can enable and disable menu items with the
enable property and so or hide then with the visible property. Note that for menu items
to be display you have to add it to a main menu (or context menu) Object.

Context Menu :
Another popular type of menus is context menus .you use context menu
controls to give users access to frequently used menu commands, and bring them up
by right clicking another control . You can see context menus to display control specific
options , such as cut ,copy and paste in textboxes.
You associate context menus with other control by setting the control’s context
menu property to context menu control. the central property of the context menu control
is the menu items property , you can add menu items to a context menu at design time
or in code by creating menu items object and adding then to the menu items collections
of the context menu . as with main menus , context menu items can be disable , hidden,
or deleted . you also can show context menus yourself with the context menu controls
show method. They hide away as soon as you click some where other then on them .
you can handle the menu items click , select and popup event as you can in main
menus . if fact the only major difference here is that context menu are not divided in to
separate menus like file ,edit ,window and so on.

ToolTip

The Windows Forms ToolTip component displays text when the user points at controls.
A ToolTip can be associated with any control. An example use of this control: In order to
save space on a form, you can display a small icon on a button and use a ToolTip to
explain the button's function.
Working with the ToolTip Component
A ToolTip component provides a ToolTip property to multiple controls on a Windows Form or
other container. For example, if you place one ToolTip component on a form, you can display
"Type your name here" for a TextBox control and "Click here to save changes" for
a Button control.

The key methods of the ToolTip component are SetToolTip and GetToolTip. You can use
the SetToolTip method to set the ToolTips displayed for controls.

Set a ToolTip programmatically


1. Add the control that will display the ToolTip.
2. Use the SetToolTip method of the ToolTip component.
// In this example, button1 is the control to display the ToolTip.
toolTip1.SetToolTip(button1, "Save changes")
Set a ToolTip in the designer
1. In Visual Studio, add a ToolTip component to the form.
2. Select the control that will display the ToolTip, or add it to the form.
3. In the Properties window, set the ToolTip on ToolTip1 value to an appropriate
string of text.
To remove a ToolTip programmatically
1. Use the SetToolTip method of the ToolTip component.
// In this example, button1 is the control displaying the ToolTip.
toolTip1.SetToolTip(button1, null)
Remove a ToolTip in the designer
1. In Visual Studio, select the control that is displaying the ToolTip.
2. In the Properties window, delete the text in the ToolTip on ToolTip1.

MDI Form
MDI stands for Multiple Document Interface applications that allow users to work with
multiple documents by opening more than one document at a time. Whereas, a Single Document
Interface (SDI) application can manipulate only one document at a time.

The MDI applications act as the parent and child relationship in a form. A parent form is
a container that contains child forms, while child forms can be multiple to display different
modules in a parent form.

VB.NET has following rules for creating a form as an MDI form.

1. MidParent: The MidParent property is used to set a parent form to a child form.
2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the
current child form.

3. IsMdiContainer: The IsMdiContainer property set a Boolean value to True that


represents the creation of a form as an MDI form.

4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent
or main form.

5. Controls: It is used to get the reference of control from the child form.

MDI (Multiple Document Interface) Application is an application in which we can view and
work with several documents at once. Example of an MDI application is Microsoft Excel.
Excel allows us to work with several documents at once. In contrast, SDI (Single Document
Interface)
applicatio
ns are the
applicatio
ns which
allows us
to work
with a
single
document
at once.
Example
of a single
document
applicatio
n is
Microsoft Word in which only one document is visible at a time. Visual Basic .NET provides
great support for creating and working with MDI applications. In general, MDI applications
are mostly used by financial services organizations where the user needs to work with
several documents at once.

Creating MDI Applications

Let's create an MDI application. Open a new Windows Application in Visual


Basic .NET. The application will open with a default form, Form1. Add another
form, Form2 to this application by right-clicking on the project name in Solution
Explorer window and selecting Add->Add Windows Form. You can add some
controls to Form2. For this application we will make From1 as the MDI parent
window and Form2 as MDI child window. MDI child forms are important for MDI
Applications as users interact mostly through child forms. Select Form1 and in
it's Properties Window under the Windows Style section, set the property
IsMdiContainer to True. Setting it to true designates this form as an MDI
container for the child windows. Once you set that property to true the form
changes it's color. Now, from the toolbox drag a MainMenu component onto
Form1. We will display child windows when a menu item is clicked. Name the
top-level menu item to File with submenu items as New Child Window, Arrange
Child Windows and Exit.

The whole form should look like the image below.

With this application a new child window is displayed each time the New Child
Window menu item is clicked, all child windows will be arranged when you click
Arrange Child Windows menu item. To get the desired result, open the code
designer window and paste the following code.

Public Class Form1 Inherits System.Windows.Forms.Form

Dim childForm As Integer = 0


Dim childForms(5) As Form2
'declaring an array to store child windows
'five child windows (Form2) will be displayed

#Region " Windows Form Designer generated code "

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _


As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub MenuItem2_Click(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles MenuItem2.Click
childForm += 1
childForms(childForm) = New Form2()
childForms(childForm).Text = "ChildForm" & Str(childForm)
'setting title for child windows and incrementing the number with an array
childForms(childForm).MdiParent = Me
childForms(childForm).Show()
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object,_


ByVal e As System.EventArgs) Handles MenuItem3.Click
Me.LayoutMdi(MdiLayout.Cascade)
'arranging child windows on the parent form with predefined LayoutMdi method
'Different layouts available are, ArrangeIcons, Cascade, TileHorizontal, TileVertical
End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal_


e As System.EventArgs) Handles MenuItem4.Click
Me.Close()
'closing the application
End Sub
End Class

When you run the application and click "New Child Window" menu item, a new child
window is displayed. Five child windows will be displayed as we declared an array of five
in code. The image below displays the output.

When you click on "Arrange Child Windows" menu item, all child windows are arranged. It
looks like the image below.

Title Make an MDI application in VB .NET

Keywords MDI, Multiple Document Interface, VB.NET

Categories VB.NET, Tips and Tricks, Controls

To make the MDI container form, make a form and set its IsMdiContainer property to True.
To make a menu list the MDI child forms, set its MdiList property to True.
Use code similar to the following to add a MDI child form to the MDI container.

Dim frm2 As New Form2


frm2.MdiParent = Me
frm2.Text = "Child " & Me.MdiChildren.GetLength(0)
frm2.Show()

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 −
Class name
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
 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 −
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
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.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 −
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

Public Sub setBreadth(ByVal bre As Double)


breadth = bre
End Sub

Public Sub setHeight(ByVal hei As Double)


height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
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
' box 1 specification
Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
' volume of box 1
volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)
'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 −


Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line : 6
A default constructor does not have any parameter, but if you need, a
constructor can have parameters. Such constructors are
called parameterized constructors. This technique helps you to assign initial
value to an object at the time of its creation as shown in the following example

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

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
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 −
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub

Protected Overrides Sub Finalize() ' destructor


Console.WriteLine("Object is being deleted")
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Function getLength() As Double
Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line : 6
Object is being deleted

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

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 −
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Total area: 35

Base Class Initialization

The derived class inherits the base class member variables and member
methods. Therefore, the super class object should be created before the
subclass is created. The super class or the base class is implicitly known
as MyBase in VB.Net
The following program demonstrates this −
' Base class
Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class

'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
Width: 7.5
Area: 33.75
Cost: 2362.5

You might also like