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

VB.Net

The document provides an overview of data types in VB .NET 2005, including elementary types such as numeric, character, and miscellaneous data types, as well as composite data types like structures and arrays. It also discusses programming practices like Option Explicit and Option Strict for variable declaration and type safety, along with the use of enumerations and import statements. Additionally, it includes examples of creating forms and handling events in a VB .NET application.

Uploaded by

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

VB.Net

The document provides an overview of data types in VB .NET 2005, including elementary types such as numeric, character, and miscellaneous data types, as well as composite data types like structures and arrays. It also discusses programming practices like Option Explicit and Option Strict for variable declaration and type safety, along with the use of enumerations and import statements. Additionally, it includes examples of creating forms and handling events in a VB .NET application.

Uploaded by

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

V.S.

PATEL BCA COLLEGE, BILIMORA


Data Type of VB .NET 2005: -
The data type of a programming element refers to what kind of data it can hold and how it stores that
data. Every variable, literal, constant, enumeration, property, procedure parameter, procedure argument, and
procedure return value has a data type.

 Elementary Data Types:-


(A) Numeric Data Types
(B) Character Data Types
(C) Miscellaneous Data Types

(A) Numeric Data Types :


(A) Integral types represent only whole numbers without fractional parts. (Positive, negative, & zero)
(B) Nonintegral types represent numbers with both integer and fractional parts.

(A) Integral Numeric Types: It represents only whole numbers without fractional parts. (Positive,
negative, & zero). It contains the signed integral data types & the unsigned integral data types.

(i) Byte: (1 Byte): Holds unsigned 8-bit (1-byte) integers ranging in value from 0 through 255.
(ii) SByte: (1 Byte): Holds Signed 8-bit (1-byte) integers ranging in value from -128 through 127.
(iii) Short: (2 Byte): Holds signed 16-bit (2-byte) integers ranging in value from -32,768 through 32,767.
(iv) UShort: (2 Byte): Holds unsigned 16-bit (2-byte) integers ranging in value from 0 through 65,535.
(v) Integer: (4 Byte): Holds signed 32-bit (4-byte) integers no.
(vi) UInteger: (4 Byte): Holds unsigned 32-bit (4-byte) integers no.
(vii) Long: (8 Byte): Holds signed 64-bit (8-byte) integers no.
(viii) ULong: (8 Byte): Holds unsigned 64-bit (8-byte) integers no.

(B) Nonintegral types represent numbers with both integer and fractional parts. (With Decimal point).

(i) Single: (4 Byte): Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers.
(ii) Double: (8 Byte): Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers.
(iii) Decimal: (16 Byte): It is a 128-bit (16 Byte) data type that provides support for cery large values
that can be scaled by powers of 10. The number of digits to the right of the decimal point can range from 0
to 28.

(B) Character Data Types :


Visual Basic provides character data types for dealing with printable and
displayable characters. While they both deal with Unicode characters, Char holds a single character while
String contains an indefinite number of characters.

(i) Char (2 Byte): The Char data type is a single two-byte (16-bit) Unicode character. If a variable
always stores exactly one character, declare it as Char.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(ii) String: The String data type is a sequence of zero or more Unicode characters. Its storage size is
depends on implementing platforms. A string can contain from 0 to approximately 2 billion (2 ^ 31)
Unicode characters.
The default value of String is Nothing (a null reference). Note that this is not the same as the empty
string (value "").

 Framework Type: The corresponding type in the .NET Framework is the System.String class.
Example: You can desclae Variable Length String variable as follows:
Dim StrMsg As String
StrMsg = “OMSHIVSAI”
OR In following example you can also declare & initialize the string as follows.
Dim StrMsg As String = “OMSHIVSAI”

Note: VB6 & earlier version supported Fixed-Length String. But that is changed in visual Basic 2005 to
match the .NET framework. However, there is a special attribute class in Visual Basic 2005 –
VBFixedStringAttribute that lets you declare Fixed-Length String. For example following example
declares a string of 10 characters.
<VBFixedStringAttribute (10)> Dim StrMsg As String
You have to import Microsoft.VisualBasic namespace.

 There are quite number of string-handling functions built into Visual Basic 2005. For example Left, Mid,
Right etc
 Besides the string-handling functions built into Visual Basic 2005, many .Net Framework functions are
built into the String class that Visual Basic 2005 uses. For example we can convert a text string to upper
case either by using Visual Basic 2005 UCase function, or the String class’s ToUpper method.

(C) Miscellaneous Data Types : Describes the Boolean, Date, and Object types.
(i) Boolean: Holds values that can be only True or False. The default value of Boolean is False. Its
storage size (data width) depends on the implementing platform.
(ii) Date (8 Byte): Holds IEEE 64-bit (8-byte) values that represent dates ranging from January 1 of the
year 0001 through December 31 of the year 9999. It holds date values, time values, or date and time value.
The default value of Date is 0:00:00 (midnight) on January 1, 0001.
(iii) Object: An Object data type is a universal data type, which can hold any type of data. An Object
variable can refer to any object your application recognizes, or to data of any data type.
You can assign any reference type (string, array, class, or interface) to an Object variable. An
Object variable can also refer to data of any value type (numeric, Boolean, Char, Date, structure, or
enumeration).

 Composite Data Types:-


In addition to the elementary data types Visual Basic also supports, composite data types such as
structures, arrays, and classes. You can build composite data types from elementary types and from other
composite types.

 Comments in VB starts with an apostrophe (‘) & make VB ignore whatever follows the apostrophe on the
line.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Option Explicit Statement :
When Option Explicit appears in a file (when it is ON), you must explicitly declare all variables using the Dim or
ReDim statements.
It is on by default, required declaration of all variables before they are used. (this is the default) If you do not
use the Option Explicit statement (when it is OFF), all undeclared variables are trated as Object type.

To set Option Explicit in the integrated development environment (IDE)


1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Explicit setting.

To set Option Explicit on the command line


Include following statement.
Option Explicit On

Example:
‘Force explicit variable declaration.
Option Explicit On
………
………
Dim thisVar As Integer
ThisVar = 10
‘The following assignment produces a COMPILER ERROR because
‘The variable is not declared and Option Explicit is on.
ThisInt = 10 ' causes ERROR

 Option Strict Statement:- It is Off by default.


When you assign value of one type to a variable of another type & if there is any possibility of data
loss .Then Visual Basic will consider that an error if this option is ON.
When Option Strict is ON, Visual Basic will not automatically convert data type when you assign a
value of one type to a variable of another. For example when you assign a double precision floating point
varable to an interger variable. An error occurs that: it disallows such implicit conversions from Double To
Integer
Because Option Strict On provides strong typing, prevents unintended type conversions with data
loss (prevents implicits narrowing type ocnversion), disallows late binding, and improves performance, its
use is strongly recommended.

To set Option Strict in the integrated development environment (IDE)


1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Strict setting.

To set Option Strict on the command line


Option Strict On

Example:

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
‘Force explicit variable declaration.
Option Strict On
………
………
Dim I As Integer
Dim D As Double
D = 3.14159

I=D ‘A compilation error occurs if such a narrowing conversion fails. It will disallows
‘Implicit conversions from Double To Integer
‘To solve above problem either you have to make Option Strict Off or you have to
‘do specific type conversion as follows.

I = Cint(D) ‘ Convert To Integer.

 Option Compare Statement:


The Option Compare statement specifies the string comparison method (Binary or Text) for a class,
module or structure. If an Option Compare statement is not included, the default text comparison method
is Binary.
Option Compare {Binary | Text }

Binary
Optional. Results in string comparisons based on a sort order derived from the
internal binary representations of the characters.
Text
Optional. Results in string comparisons based on a case-insensitive text sort
order determined by your system's locale.
Option Compare Binary, which produces a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø
When the same characters in the same code page are sorted using
Option Compare Text, the following text sort order is produced.
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)

To set Option Compare in the integrated development environment (IDE)


1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Compare setting.

To set Option Compare on the command line


‘Set the string comparison method to Binary ("AAA" < "aaa").
Option Compare Binary
‘Set the string comparison method to Text ("AAA" = "aaa").
Option Compare Text

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Import Statement:-
You can use Import statements to import a namespace so you don’t have to qualify items in that
namespace by listing the entrire namespace when you refer to item. For example: WriteLine procedure is
built into System.Console namespace, so it is a method of that namespace.

System.Console.WriteLine (“Faith Brings The Pure Megic”)

On other hand, if we import the System.Console namespace, that makes the namespace immediately
available. WriteLine (“Faith Brings The Pure Megic”)

 Enumeration:-Constants are a way to use meaningful names in place of a


Value that does not change. Constants store values that, as the name implies, remain constant throughout the
execution of an application. You can use constants to provide meaningful names, instead of numbers,
making your code more readable.
Enumerations provide a convenient way to work with sets of related constants, and to associate
constant values with names. For example, you can declare an enumeration for a set of integer constants
associated with the days of the week, and then use the names of the days rather than their integer values in
your code. Visual Basic provides a number of useful enumerations (pre-defined enumeration).
For example MsgBoxResult Enumeration, MsgBoxStyle Enumeration, DateFormat Enumeration, etc.
Custom Define Enumerations:
Syntax:

Enum enumeration name [ As data type ]


Member list
End Enum
 You create an enumeration with the Enum statement in the declarations section of a class or module
or at procedure or block level.
 The underlying type must be one of the integer types— you can specify Byte, Integer, Long, SByte,
Short, UInteger, ULong, or UShort. By default is Integer.

Example: The following example of enumerations that assign a constant to every day of the week.
Enum Days
Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7
End Enum

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
To use constant in the enumeration, you refer to like this: Days.Friday
Days.Thursday
The following code example creates a new instance of a Form and calls the ShowDialog method to
display the form as a dialog box. The example sets the FormBorderStyle, AcceptButton, CancelButton,
MinimizeBox, MaximizeBox, and StartPosition properties to change the appearance and functionality of the
form to a dialog box. The example also uses the Add method of the form's Controls collection to add two
Button controls. The example uses the HelpButton property to display a help button in the caption bar of the
dialog box.

Public Sub CreateMyForm ()


‘Create a new instance of the form.
Dim form1 As New Form ()
‘Create two buttons to use as the accept and cancel buttons.

Dim button1 As New Button()


Dim button2 As New Button()
' Set the text of button1 to "OK".
button1.Text = "OK"
' Set the position of the button on the form.
button1.Location = New Point(10, 10)
' Set the text of button2 to "Cancel".
button2.Text = "Cancel"
' Set the position of the button based on the location of button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top + 10)
' Set the caption bar text of the form.
form1.Text = "My Dialog Box"
' Display a help button on the form.
form1.HelpButton = True

' Define the border style of the form to a dialog box.


form1.FormBorderStyle = FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = False
' Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = False
' Set the accept button of the form to button1.
form1.AcceptButton = button1
' Set the cancel button of the form to button2.
form1.CancelButton = button2
' Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen

' Add button1 to the form.


form1.Controls.Add(button1)
' Add button2 to the form.
form1.Controls.Add(button2)

' Display the form as a modal dialog box.


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
form1.ShowDialog()

End Sub

 DateTime Objact page no 281,282,280 &


Elapsed Time object:-

Public Class Form1


Dim RTB1 As New RichTextBox()

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


System.EventArgs) Handles NewToolStripMenuItem.Click
'RTB1 = New System.Windows.Forms.RichText
RTB1.SetBounds(50, 50, 500, 500)
Me.Controls.Add(RTB1)
End Sub

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


System.EventArgs) Handles OpenToolStripMenuItem.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = "D:\"
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.FilterIndex = 2

OpenFileDialog1.ShowDialog()
RTB1.LoadFile(OpenFileDialog1.FileName)
End Sub

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


System.EventArgs) Handles CloseToolStripMenuItem.Click
Me.Controls.Remove(RTB1)
RTB1.Text = ""
End Sub

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


System.EventArgs) Handles SaveToolStripMenuItem1.Click
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
SaveFileDialog1.ShowDialog()
RTB1.SaveFile(SaveFileDialog1.FileName)
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
End Sub

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


System.EventArgs) Handles PToolStripMenuItem.Click
' Determine if there is any text in the Clipboard to paste into the text box.
If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
' Paste current text in Clipboard into text box.
RTB1.Paste()
End If
End Sub

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


System.EventArgs) Handles FontToolStripMenuItem.Click
FontDialog1.ShowDialog()
RTB1.SelectionFont = FontDialog1.Font
End Sub

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


System.EventArgs) Handles ColourToolStripMenuItem.Click
ColorDialog1.ShowDialog()
RTB1.SelectionColor = ColorDialog1.Color
End Sub

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


System.EventArgs) Handles CutToolStripMenuItem.Click
' Ensure that text is currently selected in the text box.
If RTB1.SelectedText <> "" Then
' Cut the selected text in the control and paste it into the Clipboard.
RTB1.Cut()
End If
End Sub

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


System.EventArgs) Handles CopyToolStripMenuItem.Click
' Ensure that text is selected in the text box.
If RTB1.SelectionLength > 0 Then
' Copy the selected text to the Clipboard.
RTB1.Copy()
End If
End Sub

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


As System.EventArgs) Handles SelectAllToolStripMenuItem.Click
RTB1.SelectAll()
End Sub

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


System.EventArgs) Handles UndoToolStripMenuItem.Click
RTB1.Undo()
End Sub

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


System.EventArgs) Handles FindToolStripMenuItem.Click
Dim s As String = InputBox("Please enter the string to search")
Dim posi As Integer = RTB1.Find(s)
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
RTB1.SelectionLength = s.Length
End Sub

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


System.EventArgs) Handles LeftToolStripMenuItem.Click
RTB1.SelectionAlignment = HorizontalAlignment.Left
End Sub

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


System.EventArgs) Handles CenterToolStripMenuItem.Click
RTB1.SelectionAlignment = HorizontalAlignment.Center
End Sub

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


System.EventArgs) Handles RightToolStripMenuItem.Click
RTB1.SelectionAlignment = HorizontalAlignment.Right
End Sub

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


System.EventArgs)

End Sub

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


System.EventArgs)
RTB1.SelectionFont = New Font(RTB1.Font, FontStyle.Bold)
End Sub
End Class

 InputBox Function:
InputBox function is used to create a modal dialog box, that is used to get (retrieve) one
piece of information (a string of text) from the user.You can use the InputBox function to get a string of
text from the user. Here's the syntax for this function: To get a multiple piece of information you have to
create your own custom dialog box.
InputBox displays a dialog box with title, message, one textbox, one OK & Cancel button.
Syntax :
InputBox (Prompt As String [, Title As String = "", DefaultResponse As String = "",
Xpos As Integer = -1, YPos As Integer = -1 ] ) As String
And here are the arguments (parameters) for this function:

 Prompt— A string expression displayed as the message in the dialog box. The maximum length is
about 1,024 characters (depending on the width of the characters used). You can separate the lines using a
carriage return character Chr(13), a line feed character Chr(10).

 Title— (Optional) String expression displayed in the title bar of the dialog box. Note that if you
omit Title, the application name is placed in the title bar.

 DefaultResponse—(Optional) A string expression displayed in the text box as the default


Response if no other input is provided. Note that if you omit DefaultResponse, the displayed text box is
empty.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 XPos—(Optional) The distance in pixels of the left edge of the dialog box from the left edge of the
screen. Note that if you omit XPos, the dialog box is centered horizontally.

 YPos— (Optional) The distance in pixels of the upper edge of the dialog box from the top of the
screen. Note that if you omit YPos, the dialog box is positioned vertically about one-third of the way down
the screen.

Example:
Dim ans As String
ans = InputBox("Please enter your name", "Demo", "OM", 300, 300)

 MsgBox Function:-
MsgBox function is used to display a message to the user & get user response (waits for the
user to click a button), and then returns an integer value indicating which button of the message box was
User clicked by the user. (For example yes, no, cancel, ok, etc).

Syntax:
MsgBox (Prompt As Object [, Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly,
Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly, Title As Object = Nothing]) As MsgBoxResult

 Prompt—A string expression displayed as the message in the dialog box. The maximum length is
about 1,024 characters (depending on the width of the characters used). You can separate the lines using a
carriage return character Chr(13), a line feed character Chr(10).

 Buttons—(Optional). The sum of values specifying the number and type of buttons to display, the
icon style to use, the identity of the default button, and the modality of the message box. If you omit Buttons,
the default value is zero, then it will display OK button).
 Title—(Optional). String expression displayed in the title bar of the dialog box. Note that if you
omit Title, the application name is placed in the title bar.

Return Value:
Note also that this function returns a value from the MsgBoxResult enumeration. Here are the
possible MsgBoxResult values, indicating which button in the message box the user clicked:

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Constant Value
OK 1

Cancel 2

Abort 3

Retry 4

Ignore 5

Yes 6

No 7

Example:

Dim Result As Integer


Result = MsgBox("Do you want to Exit?", MsgBoxStyle.YesNo + MsgBoxStyle.Question +
MsgBoxStyle.SystemModal + MsgBoxStyle.DefaultButton2, "Quit")
If (Result = MsgBoxResult.Yes) Then
Me.Close()
End If

You can find the possible constants to use for the Buttons argument as follows. (The MsgBoxStyle
enumeration values are as follows).

Constant Value Description

OKOnly 0 Displays OK button only.

OKCancel 1 Displays OK and Cancel buttons.

AbortRetryIgnore 2 Displays Abort, Retry, and Ignore buttons.

YesNoCancel 3 Displays Yes, No, and Cancel buttons.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
YesNo 4 Displays Yes and No buttons.

RetryCancel 5 Displays Retry and Cancel buttons.

Critical 16 Displays Critical Message icon.

Question 32 Displays Warning Query icon.

Exclamation 48 Displays Warning Message icon.

Information 64 Displays Information Message icon.

DefaultButton1 0 First button is default.

DefaultButton2 256 Second button is default.

DefaultButton3 512 Third button is default.

Application is modal. The user must respond to the message box


ApplicationModal 0
before continuing work in the current application.

System is modal. All applications are suspended until the user


SystemModal 4096
responds to the message box.

MsgBoxSetForeground 65536 Specifies the message box window as the foreground window.

MsgBoxRight 524288 Text is right-aligned.

Specifies text should appear as right-to-left reading on Hebrew and


MsgBoxRtlReading 1048576
Arabic systems.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 MessageBox.Show Method:-
You can also use the Show method MessageBox class built into the .NET Framework to display
messages and accept input from the user. This method has many overloaded forms.
The title, message, buttons, and icons displayed in the message box are determined by parameters
that you pass to this method.

MessageBox.Show (Text As String, Caption As String, Buttons As MessageBoxButtons,


Icon As MessageBoxIcon, DefaultButton As MessageBoxDefaultButton,
Options As MessageBoxOptions) As DialogResult

Here are the arguments you pass to this method:-

 Text—The text to display in the message box.


 Caption—The text to display in the title bar of the message box.
 Buttons—One of the MessageBoxButtons enumeration values that specifies which buttons to
display in the message box. See below.
 Icon—One of the MessageBoxIcon enumeration values that specifies which icon to display in the
message box. See below.
 DefaultButton—One of the MessageBoxDefaultButton enumeration values that specifies which
is the default button for the message box. See below.
 Options—One of the MessageBoxOptions enumeration values that specifies which display and
association options will be used for the message box. See below.

Example:

Dim Result As Integer


Result = MessageBox.Show("Do you want to Exit?", "Quit", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If (Result = DialogResult.Yes) Then
Me.Close()
End If

Here are the MessageBoxButtons enumeration values:

 AbortRetryIgnore— The message box will show Abort, Retry, and Ignore buttons.
 OK— The message box will show an OK button.
 OKCancel— The message box will show OK and Cancel buttons.
 RetryCancel— The message box will show Retry and Cancel buttons.
 YesNo— The message box will show Yes and No buttons.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 YesNoCancel— The message box will show Yes, No, and Cancel buttons.

Here are the MessageBoxIcon enumeration values:

 Asterisk— Shows an icon displaying a lowercase letter i in a circle.


 Error— Shows an icon displaying a white X in a circle with a red background.
 Exclamation— Shows an icon displaying an exclamation point in a triangle with a yellow
background.
 Hand— Shows an icon displaying a white X in a circle with a red background.
 Information— Shows an icon displaying a lowercase letter i in a circle.
 None— Shows no icons.
 Question— Shows an icon displaying a question mark in a circle.
 Stop— Shows an icon displaying white X in a circle with a red background.
 Warning— Shows an icon displaying an exclamation point in a triangle with a yellow
background.

Here are the MessageBoxDefaultButton enumeration values:

 Button1— Makes the first button on the message box the default button.
 Button2— Makes the second button on the message box the default button.
 Button3— Makes the third button on the message box the default button.

Here are the MessageBoxOptions enumeration values:

 DefaultDesktopOnly— Displays the message box on the active desktop.


 RightAlign— The message box text is right-aligned.
 RtlReading— Specifies that the message box text is displayed with right to left reading order.

The result of the Show method is a value from the DialogResult enumeration, showing what button
the user clicked:

 Abort— Returns Abort.


 Cancel— Returns Cancel.
 Ignore— Returns Ignore.
 No— Returns No.
 None— Nothing is returned from the dialog box. (Note that this means that a modal dialog
continues running.)
 OK— Returns OK.
 Retry— Returns Retry.
 Yes— Returns Yes.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Exception Handling:
There are two ways of handling errors that occur at run time in VB 2005 –
(A) With Unstructured exception handling: The On Error statement is used specifically for
unstructured exception handling.

(B) With Structured exception handling: Structured exception handling uses the
Try…Catch…Finally statement.
Without an On Error GoTo or Try…Catch…Finally statement, any exception that occurs is fatal
and your program will stop.

 Structured exception handling:


(Trapping Error Using Structure error handling):
Try
‘Place statements that may produce a runtime error(that may throw an exception) in this block.
[Catch <exception1> As <type1> [When expression1]]
‘Place statements that take some action if an exception is thrown.
[Exit Try]]
[Additional Catch blocks]
Finally
‘This code always runs whether an error occur or not
End Try

Structured exception handling is based on a particular statement, the Try…Catch…Finally statement,


which is divided into a Try block, optional Catch blocks, and an optional Finally block.
The Try block contains the section of code to be monitored for exceptions. (contains code where
exceptions can occur).

The Catch block contains code to handle the exceptions that occur. If an exception occurs in the Try
block, the code throws the exception. If an error occurs during execution of Try clock, Visual Basic
examines each Catch statement within the Try...Catch...Finally until it finds one with a condition that
matches that error.

The code in the Finally block always executes last, regardless of whether the code in the Catch
blocks has executed. Place cleanup code, such as that for closing files and releasing objects, in the Finally
section.

Note: If a Try statement does not contain any Catch blocks, it must contain a Finally block
Note: You can have any number of Catch statements (however, you must have at least one Catch
statement or a Finally statement).
Example:
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Dim x As Double = 5 ' Declare variables.
Dim y As Integer = 0
Try ' Set up structured error handling.
x /= y ' Cause a "Divide by Zero" error.
Catch ex As Exception When y = 0 ' Catch the error.
MsgBox(ex.ToString) ' Show friendly error message.
Finally
Beep() ' This line is executed no matter what.
End Try

 ToString Method: We can use exception object's ToString method to display information about
the exception.

 For the user, you might display the message in the exception object's message property (that is, use
e.message instead), which gives you this:
That's a little better, but of course, it's best to catch individual exceptions yourself and to customize
the messages you display to your application.

 Error Filtering in the Catch Block:


There are actually two ways to filter exceptions with Catch blocks.
(a) You can filter on specific classes of exceptions &
(b) Second, You can filter using the When keyword.

(A) You can filter on specific classes of exceptions. Exceptions are based on the Visual Basic
Exception class. For example when you divide two numbers and an overflow exception occurs.
Example:

Dim A = 1, B = 0, Z As Integer
Try
Z=A/B
MsgBox("The answer is :" & Z)
Catch exp As System.OverflowException
MsgBox("Exception: Arithmetic overflow!")
End Try

(B) You can filter using the When keyword. The second exception-filtering option lets you use the
Catch statement to filter on any conditional expression, using the When keyword. This option is often used
to filter by exception number, which you can check with the Err object's Number property. Here's an
example that filters overflow exceptions by number (which is exception number 6 in Visual Basic .NET):
Example:
Dim A = 1, B = 0, Z As Integer
Try
Z=A/B
MsgBox("The answer is :" & Z)
Catch When Err.Number = 6
MsgBox("Exception: Arithmetic overflow")
End Try
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 If you want to add a general exception handler to catch any exceptions not filtered, you can add a
Catch block for the Exception class at the end of the other Catch blocks:
Dim A = 1, B = 0, Z As Integer
Try
Z=A/B
MsgBox("The answer is :" & Z)
Catch exp As System.OverflowException
MsgBox("Exception: Arithmetic overflow")
Catch e As System.ArgumentException
MsgBox("Exception: Invalid argument value”)
Catch exp As Exception
MsgBox("Exception occurred”)
End Try

 Err Object:
Err object Contains information about run-time errors.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely
identifies the error and that you can use to handle the error. The Number property of the Err object contains
the number of the most recent run time error, and the Description property contains a text message that
describes the error in detail.

You can clear the Err object by using the Err.Clear method.
To generate a run-time error in your code, use the Raise method.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Menu: -
The menu bar appears immediately below the title bar on the form & contains one or more menu
items. Each menu item on the menu bar can display another menu called the sub menu, containing some
more menu items. The items on the sub menu are called sub menu items.

MenuStrip Control: OR MainMenu Control:


The MenuStrip control is new addition in Visual Studio 2005 and the .NET Framework version 2.0.
With the control, you can easily create menus like those found in Microsoft Office. You can enhance the
usability and readability of your menus by adding access keys, shortcut keys, check marks, images, and
separator bars.
The MenuStrip control represents the container of ToolStripMenuItem objects. Any item that
resides on a menu is called a menu item & represents an individual part of the menu.
The MenuStrip control supports the multiple-document interface (MDI) and menu merging, tool
tips, and overflow.

 Property :-
(1) Items: - Gets all the items that belong to a ToolStrip. Use the Items collection to retrieve all the items
that have been added to the ToolStrip. Use the DisplayedItems property to retrieve only the items that are
currently displayed on the ToolStrip.

(2) ImageList: Gets or sets the image list that contains the image displayed on a ToolStrip item.

(3) MdiWindowListItem: Gets or sets the ToolStripMenuItem that is used to display a list of MDI
child forms.

 Event: -
(1) ItemClicked: Occurs when the ToolStripItem is clicked.

(2) ItemRemoved: Occurs when a ToolStripItem is removed from the ToolStripItemCollection.

(3) ItemAdded: Occurs when a new ToolStripItem is added to the ToolStripItemCollection.

ToolStripMenuItem : OR MenuItem:
ToolStripMenuItem is a collection of the items in the menu. Any item that resides on a menu is
called a menu item & represents an individual part of the menu. ToolStripMenuItem class enables you to
configure the appearance & functionality of the menu item. For example you can display a check mark next
to a menu item, create a menu separator, assign shortcut keys to menu items, add images to the menu items
etc.
In order for a ToolStripMenuItem to be displayed, you must add it to a MenuStrip or
ContextMenuStrip.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Property :-
(1) Checked: Gets or sets a value indicating whether the ToolStripMenuItem is checked. This property
indicates whether the specified menu item will have a check mark beside its text. If this property is set to
true, then a check mark is placed beside the specified menu item.
(2) CheckState: Gets or sets a value indicating whether a ToolStripMenuItem is in the checked,
unchecked, or indeterminate state.
(3) IsMdiWindowListEntry: Gets a value indicating whether the ToolStripMenuItem appears on a
multiple document interface (MDI) window list. If this property is set to true, then the name of the active
child windows will be displayed in the menu item.
(4) Text:

Context Menus:-
Set the menu command's ShortcutKeyDisplayString property to the desired keyboard combination,
such as CTRL+SHIFT+O rather than SHIFT+CTRL+O, and set the ShowShortcutKeys property to true.

To display an access key for a menu command


When you set the Text property for the menu command, enter an ampersand (&) before the letter you
want to be underlined as the access key. For example, typing &Open as the Text property of a menu item
will result in a menu command that appears as Open.

To navigate to this menu command, press ALT to give focus to the MenuStrip, and press the access
key of the menu name. When the menu opens and shows items with access keys, you only need to press the
access key to select the menu command.
Note: - Avoid defining duplicate access keys, such as defining ALT+F twice in the same menu system.
The selection order of duplicate access keys cannot be guaranteed.

To display a separator bar between menu commands


After you define your MenuStrip and the items it will contain, use the AddRange or Add method to
add the menu commands and ToolStripSeparator controls to the MenuStrip in the order you want.

[Visual Basic]
‘This code adds a top-level File menu to the MenuStrip.
Me.menuStrip1.Items.Add (New ToolStripMenuItem () _
{Me.fileToolStripMenuItem})

‘This code adds the New and Open menu commands, a separator bar,
‘And the Save and Exit menu commands to the top-level File menu,
‘In that order.
Me.fileToolStripMenuItem.DropDownItems.AddRange (New _

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
ToolStripMenuItem () {Me.newToolStripMenuItem, _
Me.openToolStripMenuItem, Me.toolStripSeparator1, _
Me.saveToolStripMenuItem, Me.exitToolStripMenuItem})

Object:-
An object is a combination of code and data that can be treated as a unit. An object can be a piece of
an application, like a control or a form. An entire application can also be an object.

Reusing Code:-
Objects let you declare variables and procedures once and then reuse them whenever needed.
For example, if you want to add a spelling checker to an application you could define all the variables and
support functions to provide spell-checking functionality. If you create your spelling checker as a class, you
can then reuse it in other applications by adding a reference to the compiled assembly. Better yet, you may
be able to save yourself some work by using a spelling checker class that someone else has already
developed.

Classes:-
Each object in Visual Basic is defined by a class. A class describes the variables, properties,
procedures, and events of an object. Objects are instances of classes; you can create as many objects you
need once you have defined a class.
To understand the relationship between an object and its class, think of cookie cutters and
cookies. The cookie cutter is the class. It defines the characteristics of each cookie, for example size and
shape. The class is used to create objects. The objects are the cookies.
Two examples in Visual Basic might help illustrate the relationship between classes and objects.

 The controls on the Toolbox in Visual Basic represent classes. When you drag a control from the
Toolbox onto a form, you are creating an object — an instance of a class
 The form you work with at design time is a class. At run time, Visual Basic creates an instance of the
form's class — that is, an object.

Multiple Instances:-
Objects newly created from a class are often identical to each other. Once they exist as individual
objects, however, their variables and properties can be changed independently of the other instances. For
example, if you add three check boxes to a form, each check box object is an instance of the CheckBox
class. The individual CheckBox objects share a common set of characteristics and capabilities (properties,
variables, procedures, and events) defined by the class. However, each has its own name, can be separately
enabled and disabled, and can be placed in a different location on the form.
Objects are the basic units of object-oriented programming. An object is an element of an application,
representing an instance of a class. Fields, properties, methods, and events are the building blocks of objects
and constitute their members.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Objects:-
An object represents an instance of a class, such as Form or Label. You must create an object
before you can access its nonshared members. To do this, you use the New keyword to specify the class
from which to create the object, and then assign the new object to an object variable.
Dim warningLabel As New System.Windows.Forms.Label
For more information, see How to: Create an Object.

Member Access:-
You access a member of an object by specifying, in order, the name of the object variable, a period
(.), and the name of the member. The following example sets the Text property of a Label object.
warningLabel.Text = "Data not saved"

Fields and Properties:-


Fields and properties represent information stored in an object. You retrieve and set their values
with assignment statements the same way you retrieve and set local variables in a procedure. The following
example retrieves the Width property and sets the ForeColor property of a Label object.
Dim warningWidth As Integer = warningLabel.Width
warningLabel.ForeColor = System.Drawing.Color.Red
Note that a field is also called a member variable.
For more information, see Property Procedures vs. Fields.

Methods:-
A method is an action that an object can perform. For example, Add is a method of the ComboBox object
that adds a new entry to a combo box.
The following example demonstrates the Start method of a Timer object.
Dim safetyTimer As New System.Windows.Forms.Timer
safetyTimer.Start ()
Note that a method is simply a procedure that is exposed by an object.
For more information, see How to: Perform Actions with Methods.

Events:-
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and
for which you can write code to respond. Events can occur as a result of a user action or program code, or
they can be caused by the system. Code that signals an event is said to raise the event, and code that
responds to it is said to handle it.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
You can also develop your own custom events to be raised by your objects and handled by other
objects. For more information, see Events and Event Handlers.

Instance Members and Shared Members:-


When you create an object from a class, the result is an instance of that class. Members that are
not declared with the Shared (Visual Basic) keyword are instance members, which belong strictly to that
particular instance. An instance member in one instance is independent of the same member in another
instance of the same class. An instance member variable, for example, can have different values in different
instances.

Members declared with the Shared keyword are shared members, which belong to the class
as a whole and not to any particular instance. A shared member exists only once, no matter how many
instances of its class you create, or even if you create no instances. A shared member variable, for example,
has only one value, which is available to all code that can access the class.

IntelliSense Listing of Members:-


IntelliSense lists members of a class when you invoke its List Members option, for example
when you type a period (.) as a member-access operator. If you type the period following the name of a
variable declared as an instance of that class, IntelliSense lists all the instance members and none of the
shared members. If you type the period following the class name itself, IntelliSense lists all the shared
members and none of the instance members. For more information, see Using IntelliSense.

See Also:-
An object is a structure containing data and methods that manipulate the data. Almost everything you
do in Visual Basic is associated with objects. If you are new to object-oriented programming, the following
terms and concepts will help you get started.

Classes and Objects:-


The words "class" and "object" are used so much in object-oriented programming that it is
easy to get the terms mixed up. Generally speaking, a class is an abstract representation of something,
whereas an object is a usable example of the thing the class represents. The one exception to this rule is
shared class members, which are usable in both instances of a class and object variables declared as the type
of the class.

Fields, Properties, Methods, and Events:-


Classes are made of fields, properties, methods, and events. Fields and properties represent
information that an object contains. Fields are like variables in that they can be read or set directly. For
example, if you have an object named "Car" you could store its color in a field named "Color."
Properties are retrieved and set like fields, but are implemented using property Get and property
Set procedures, which provide more control on how values are set or returned. The layer of indirection

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
between the value being stored and the procedures that use this value helps isolate your data and allows you
to validate values before they are assigned or retrieved.
Methods represent actions that an object can perform. For example, a "Car" object could have
"StartEngine," "Drive," and "Stop" methods. You define methods by adding procedures, either Sub routines
or functions, to your class.
Events are notifications an object receives from, or transmits to, other objects or applications.
Events allow objects to perform actions whenever a specific occurrence takes place. An example of an event
for the "Car" class would be a "Check_Engine" event. Because Microsoft Windows is an event-driven
operating system, events can come from other objects, applications, or user input such as mouse clicks or
key presses.

Encapsulation, Inheritance, and Polymorphism:-


Fields, properties, methods, and events are only one half of the object-oriented programming
equation. True object-orient programming requires objects to support three qualities: encapsulation,
inheritance, and polymorphism.
Encapsulation means that a group of related properties, methods, and other members are
treated as a single unit or object. Objects can control how properties are changed and methods are executed.
For example, an object can validate values before allowing property changes. Encapsulation also makes it
easier to change your implementation at a latter date by letting you hide implementation details of your
objects, a practice called data hiding.
Inheritance describes the ability to create new classes based on an existing class. The new
class inherits all the properties and methods and events of the base class, and can be customized with
additional properties and methods. For example, you can create a new class named "Truck" based on the
"Car" class. The "Truck" class inherits the "Color" property from the "Car" class and can have additional
properties such as "FourWheelDrive."
Polymorphism means that you can have multiple classes that can be used
interchangeably, even though each class implements the same properties or methods in different ways.
Polymorphism is essential to object-oriented programming because it allows you to use items with the same
names, no matter what type of object is in use at the moment. For example, given a base class of "Car,"
polymorphism enables the programmer to define different "StartEngine" methods for any number of derived
classes. The "StartEngine" method of a derived class named "DieselCar" may be completely different from
the method with the same name in the base class. Other procedures or methods can use the "StartEngine"
method of the derived classes in exactly the same way, no matter what type of "Car" object is being used at
the time.

Overloading, Overriding, and Shadowing:-


Overloading, overriding, and shadowing are similar concepts that can be easy to confuse.
Although all three techniques allow you to create members with the same name, there are some important
differences.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Overloaded members are used to provide different versions of a property or method that have the
same name, but that accept different number of parameters, or parameters with different data types

Overridden properties and methods are used to replace an inherited property or method that is not
appropriate in a derived class. Overridden members must accept the same data type and number of
arguments. Derived classes inherit overridden members.

Shadowed members are used to locally replace a member that has broader scope. Any type can
shadow any other type. For example, you can declare a property that shadows an inherited method with the
same name. Shadowed members cannot be inherited.

Overview of Microsoft .NET Framework


1.1 The .NET Framework
1.2 The Common Language Runtime (CLR)
1.3 The .NET Framework Class Library

What is .NET?
 It is a platform neutral framework. (It is a new, easy, and extensive programming platform.)
 Is a layer between the operating system and the programming language.
 It supports many programming languages, including VB.NET, C# , J# etc.
 NET provides a common set of class libraries, which can be accessed from any .NET based
programming language. There will not be separate set of classes and libraries for each language. If
you know any one .NET language, you can write code in any .NET language!! The most recent
.Net Framework version is capable of supporting over 20 different programming languages
today.

 In future versions of Windows, .NET will be freely distributed as part of operating system and users
will never have to install .NET separately. The .NET Framework is included with Windows Server
2003, Windows Server 2008 and Windows Vista, and can be installed on most older versions of
Windows.

What is Net ?
 .NET is not an operating system.
 .NET is not a programming language.

".NET is a framework"
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Are you confused by this definition? Well, that is OK. It is really confusing!
We cannot define .NET as a 'single thing'. It is a new, easy, and extensive programming
platform. It is not a programming language, but it supports several programming languages. The .NET
Framework is an environment for developing and executing applications. By default .NET comes with
few programming languages including C# (C Sharp), VB.NET, J# and managed C++. .NET is a common
platform for all the .NET supported languages. It gives a common class library, which can be called from
any of the supported languages. So, developers need not learn many libraries when they switch to a different
language. Only the syntax is different for each language.

When you write code in any language and compile, it will be converted to an 'Intermediate
Language' (Microsoft Intermediate Language - MSIL). So, your compiled executable contains the IL and not
really executable machine language. When the .NET application runs, the .NET framework in the target
computer take care of the execution. (To run a .NET application, the target computer should have .NET
framework installed.) The .NET framework converts the calls to .NET class libraries to the corresponding
APIs of the Operating system.

Whether you write code in C# or VB.NET, you are calling methods in the same .NET class
libraries. The same .NET framework executes the C# and VB.NET applications. So, there won't be any
performance difference based on the language you write code.

The .NET Framework is a environment for developing and executing applications. The .NET
Framework manages all aspects of program execution, like, allocation of memory for the storage of data and
instructions, granting and denying permissions to the application, managing execution of the application and
reallocation of memory for resources that are not needed.

The .NET Framework is designed for cross-language compatibility. Cross-language compatibility


means, an application written in Visual Basic .NET may reference a DLL file written in C# (C-Sharp). A
Visual Basic .NET class might be derived from a C# class or vice versa.

 Version of .Net Framework :


(1) .Net Framework 1.0
(2) .Net Framework 1.1
(3) .Net Framework 2.0
(4) .Net Framework 3.0
(5) .Net Framework 3.5

The .NET Framework consists of two main components:


(1) Common Language Runtime (CLR)
(2) Class Libraries

(1) Common Language Runtime (CLR):-


The CLR is described as the "execution engine" of .NET. It provides the environment within
which the programs run.
It's this CLR that manages the
 Execution of programs and provides important services, such as
 Code compilation,
 Memory allocation (memory management),
 Thread management,
 Garbage collection
 Exception handling

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Security mechanisms etc
Working of the CLR:
When the .NET program is compiled, the output of the compiler is not an executable file but a file that
contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set
of instructions understood by the common language run time. So, your compiled executable contains the IL
and not really executable machine language. This MSIL defines a set of portable instructions that are
independent of any specific CPU.

It's the job of the CLR to translate this Intermediate code into an executable. When the .NET
application runs, the .NET framework in the target computer take care of the execution. (To run a .NET
application, the target computer should have .NET framework installed.) The .NET framework converts the
calls to .NET class libraries to the corresponding APIs of the Operating system.

(And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code
using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR
activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part
of the program is needed.)

(2) Class Libraries:-


Class library is the second major entity of the .NET Framework which is designed to integrate with
the common language runtime. This library gives the program access to runtime environment. The class
library consists of lots of prewritten code that all the applications created in VB .NET and Visual Studio
.NET will use. The presence of many libraries in .NET Framework can assist you in developing your
applications in a faster, cheaper and easier manner. The code for all the elements like forms, controls and
the rest in VB .NET applications actually comes from the class library.

This class library constitutes various predefined functional sets that are very useful while
developing the applications by developers. There are three main components in this class library and they
are: (1) ·ASP.NET. (2) Windows Forms. & (3) ADO.NET.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

NET Framework Advantages :-


The .NET Framework offers a number of advantages to developers. The following paragraphs
describe them in detail.
Consistent Programming Model: Different programming languages have different
approaches for doing a task. For example, accessing data with a VB 6.0 application and a VC++
application is totally different. When using different programming languages to do a task, a disparity
exists among the approach developers use to perform the task. The difference in techniques comes
from how different languages interact with the underlying system that applications rely on.
With .NET, for example, accessing data with a VB .NET and a C# .NET looks very similar apart
from slight syntactical differences. Because both languages accessing the common .NET classes library.
Both the programs need to import the System.Data namespace, both the programs establish a
connection with the database and both the programs run a query and display the data on a data grid.

Direct Support for Security: With .NET, the Framework enables the developer and the
system administrator to specify method level security. It uses industry-standard protocols such as
TCP/IP, XML, SOAP and HTTP to facilitate distributed application communications. This makes

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
distributed computing more secure because .NET developers cooperate with network security devices
instead of working around their security limitations.
Simplified Development Efforts: Let’s take a look at this with Web applications. With classic
ASP, when a developer needs to present data from a database in a Web page, he is required to write
the application logic (code) and presentation logic (design) in the same file. He was required to mix the
ASP code with the HTML code to get the desired result.
ASP.NET and the .NET Framework simplify development by separating the application logic and
presentation logic making it easier to maintain the code. You write the design code (presentation logic)
and the actual code (application logic) separately eliminating the need to mix HTML code with ASP
code. ASP.NET can also handle the details of maintaining the state of the controls, such as contents in
a textbox, between calls to the same ASP.NET page.
Another advantage of creating applications is debugging. Visual Studio .NET and other third
party providers provide several debugging tools that simplify application development. The .NET
Framework simplifies debugging with support for Runtime diagnostics. Runtime diagnostics helps you
to track down bugs and also helps you to determine how well an application performs. The .NET
Framework provides three types of Runtime diagnostics: Event Logging, Performance Counters and
Tracing.
Easy Application Deployment and Maintenance: The .NET Framework makes it easy to
deploy applications. In the most common form, to install an application, all you need to do is copy the
application along with the components it requires into a directory on the target computer. The .NET
Framework handles the details of locating and loading the components an application needs, even if
several versions of the same application exist on the target computer. The .NET Framework ensures
that all the components the application depends on are available on the computer before the
application begins to execute.

 What is Visual Basic .NET?


Visual Basic .NET is a pure object oriented programming language
implemented on Microsoft .NET framework. It makes programmer’s life very easy.

Visual Basic .NET provides the easiest, most productive language and tool for rapidly building
Windows and Web applications. Visual Basic .NET comes with enhanced visual designers, increased
application performance, and a powerful integrated development environment (IDE). It also supports
creation of applications for wireless, Internet-enabled hand-held devices. The following are the features of
Visual Basic .NET with .NET Framework 1.0 and Visual Basic .NET 2003 with .NET Framework 1.1.

 Versions Of Visual Basic .NET:


As of November 2007, there are four versions of Visual Basic .NET that were
implemented by Visual Basic Team.

 Visual Basic .Net (VB7) Released in 2002


 Visual Basic .Net 2003 (VB7.1)
 Visual Basic .Net 2005 (VB8.0)
 Visual Basic .Net 2008 (VB9.0)
Visual Basic 10, also known as VBx, will support for Dynamic Language Runtime.
Powerful Windows-based Applications: Visual Basic .NET comes with features such as a
powerful new forms designer, an in-place menu editor, and automatic control anchoring and docking.
Visual Basic .NET delivers new productivity features for building more robust applications easily and
quickly. With an improved integrated development environment (IDE) and a significantly reduced
startup time, Visual Basic .NET offers fast, automatic formatting of code as you type, improved
IntelliSense, an enhanced object browser and XML designer, and much more.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Building Web-based Applications: With Visual Basic .NET we can create Web applications
using the shared Web Forms Designer and the familiar "drag and drop" feature. You can double-click
and write code to respond to events. Visual Basic .NET 2003 comes with an enhanced HTML Editor for
working with complex Web pages. We can also use IntelliSense technology and tag completion, or
choose the WYSIWYG editor for visual authoring of interactive Web applications.
Simplified Deployment: With Visual Basic .NET we can build applications more rapidly and
deploy and maintain them with efficiency. Visual Basic .NET 2003 and .NET Framework 1.1 makes "DLL
Hell" a thing of the past. Side-by-side versioning enables multiple versions of the same component to
live safely on the same machine so that applications can use a specific version of a component. XCOPY-
deployment and Web auto-download of Windows-based applications combine the simplicity of Web
page deployment and maintenance with the power of rich, responsive Windows-based applications.
Powerful, Flexible, Simplified Data Access: You can tackle any data access scenario easily
with ADO.NET and ADO data access. The flexibility of ADO.NET enables data binding to any database,
as well as classes, collections, and arrays, and provides true XML representation of data. Seamless
access to ADO enables simple data access for connected data binding scenarios. Using ADO.NET, Visual
Basic .NET can gain high-speed access to MS SQL Server, Oracle, DB2, Microsoft Access, and more.
Improved Coding: You can code faster and more effectively. A multitude of enhancements to
the code editor, including enhanced IntelliSense, smart listing of code for greater readability and a
background compiler for real-time notification of syntax errors transforms into a rapid application
development (RAD) coding machine.
Direct Access to the Platform: Visual Basic developers can have full access to the capabilities
available in .NET Framework 1.1. Developers can easily program system services including the event
log, performance counters and file system. The new Windows Service project template enables to build
real Microsoft Windows NT Services. Programming against Windows Services and creating new
Windows Services is not available in Visual Basic .NET Standard, it requires Visual Studio 2003
Professional, or higher.
Full Object-Oriented Constructs: You can create reusable, enterprise-class code using full
object-oriented constructs. Language features include full implementation inheritance, encapsulation,
and polymorphism. Structured exception handling provides a global error handler and eliminates
spaghetti code.
XML Web Services: XML Web services enable you to call components running on any platform
using open Internet protocols. Working with XML Web services is easier where enhancements simplify
the discovery and consumption of XML Web services that are located within any firewall. XML Web
services can be built as easily as you would build any class in Visual Basic 6.0. The XML Web service
project template builds all underlying Web service infrastructure.
Mobile Applications : Visual Basic .NET 2003 and the .NET Framework 1.1 offer integrated
support for developing mobile Web applications for more than 200 Internet-enabled mobile devices.
These new features give developers a single, mobile Web interface and programming model to support
a broad range of Web devices, including WML 1.1 for WAP—enabled cellular phones, compact HTML
(cHTML) for i-Mode phones, and HTML for Pocket PC, handheld devices, and pagers. Please note,
Pocket PC programming is not available in Visual Basic .NET Standard, it requires Visual Studio 2003
Professional, or higher.
COM Interoperability: You can maintain your existing code without the need to recode. COM
interoperability enables you to leverage your existing code assets and offers seamless bi-directional
communication between Visual Basic 6.0 and Visual Basic .NET applications.
Reuse Existing Investments: You can reuse all your existing ActiveX Controls. Windows
Forms in Visual Basic .NET 2003 provide a robust container for existing ActiveX controls. In addition,
full support for existing ADO code and data binding enable a smooth transition to Visual Basic .NET
2003.
Upgrade Wizard: You upgrade your code to receive all of the benefits of Visual Basic .NET
2003. The Visual Basic .NET Upgrade Wizard, available in Visual Basic .NET 2003 Standard Edition, and
higher, upgrades up to 95 percent of existing Visual Basic code and forms to Visual Basic .NET with
new support for Web classes and UserControls.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 What is Visual Studio.NET?


Many people always get confused with Visual Studio .NET (VS.NET) and .NET technology.
VS.NET is just an editor, provided by Microsoft to help developers write .NET programs easily. VS.NET
editor automatically generates lot of code, allow developers to drag and drop controls to a form, provide
short cuts to compile and build the application etc.
VS.NET is not a required thing to do .NET programming. You can simply use a notepad or any
other simple editor to write your .NET code!!! And you can compile your .NET programs from the
command prompt.
Well, what I said is true theoretically... but if you decide to use notepad for .NET programming, by
the time you develop few sample applications, Microsoft would have introduced some other new technology
and .NET would be outdated. You may not want that. So, let us go by VS.NET, just like every other .NET
guys.

Minimum System Requirements to Install and Use Visual Studio .NET


The minimum requirements are:
RAM: 256 MB (Recommended)
Processor: Pentium II 450 MHz
Operating System: Windows 2000 or Windows XP
Hard Disk Space: 3.5 GB (Includes 500 MB free space on disk)

C# or VB.NET? Which one to choose?


As we mentioned in earlier chapters, it makes no much difference. Whether you write code in
VB.NET or C#, when you compile, your code will get converted to MSIL (Microsoft Intermediate
language). It is this MSIL which you deliver to your customer in the form of a DLL or EXE. The MSIL is
executed by the same .NET framework, whether you wrote it originally in C# or VB.NET.

The MSIL generated by C# and VB.NET is almost 99% is the same! Many believe that C# has
the power of C++ and VB.NET has the user friendliness of VB. That is not true. Both are equally powerfull
and friendly. VB.NET has backward compatibility with old Visual basic. So, it supports old vb functions.
C# is a fresh, clean language. So strongly support using C# instead of VB.NET just for this clean compiler.

Many old VB guys usually like to stick with VB.NET and are kind of scared of C#. We are sure that
you will not take more than few days to get familiar with C# syntax. This online tutorial is based on C# and
all samples will be provided in C#.

Is it platform independent?
Many people ask this question "Java is platform independent, what about .NET?”
The answer is "Yes" and "No”!
The code you write is platform independent, because whatever you write is getting compiled into MSIL.
There is no native code, which depends on your operating system or CPU. But when you execute the
MSIL, the .NET framework in the target system will convert the MSIL into native platform code.
So, if you run your .NET exe in a Windows machine, the .NET framework for Windows will convert
it into Windows native code and execute. If you run your .NET application in Unix or Linux, the .NET
framework for Unix/Linux will convert your code into Unix/Linux native code and execute. So, your code is
purely platform independent and runs anywhere!

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
But wait, we said it wrong... there is no .NET framework for Unix or Linux available now. Microsoft
has written the .NET framework only for Windows. If you or some one else write a .NET framework for
other platforms in future, your code will run there too. So, let us wait until someone write .NET framework
for Linux before you run your .NET code in Linux.

 Object-Oriented Programming:-
Just about everything you do in Visual Basic 2005 involves objects in some way—even simple
variables are based on the Visual Basic Object class. Visual Basic comes with thousands of built-in classes.
We knew that Windows forms are classes, of course, based on the System.Windows.Forms.Form class.
The controls on the Toolbox in Visual Basic represent classes. When you drag a control from the
Toolbox onto a form, you are creating an object. For example controls such as text boxes are really based on
the TextBox class.
Just think of the numeric data types like Integer, which is a type, and a specific integer variable,
myInteger233, which is an instance of that type. In fact, the Integer type is a class in Visual Basic, and
variables of that type are in fact objects.
.Net framework follows the Object Oriented approach that is built upon classes and objects.
Classes are the basis of all the objects. A class can be defined as a template for creating different objects.
A class contains the characteristics and functionalities that objects can posses. For example in Train class
will posses the characteristics (properties) like engine, colour, no_of_coaches etc and functionalities
(methods) like move, start, stop etc.
Each object in Visual Basic is defined by a class. A class describes the Fields (variables), Properties,
Methods, and Events of an object. Classes are made of fields, properties, methods, and events.
Fields (variables), Properties, Methods, and Events are called the members of a class. Inside the
class, members are declared as either Public, Private, Protected, Friend, or Protected Friend. (Access
modifier)
It's easy to create classes and objects in Visual Basic. To create a class, you only need to use the
Class statement, needs to end with End Class:

Public Class ClassName


-----
-----
-----
End Class

Example:

Public Class Vehicle


-----
-----
-----
End Class

Objects are instances of classes; you can create as many objects you need once you have defined a
class. You must use the New keyword to create a new instance of a class:

Dim Car As New Vehicle ()


OR
Dim Car As Vehicle = New Vehicle ()
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
OR
- If you omit the New keyword, you're just declaring a new object, and it's not yet created:
Dim Car As Vehicle
-Before using the object, you must explicitly create it with New:
Car = New Vehicle ()

 Fields : -
Fields are like variables in that they can be read or set directly. For example, if you have an object
named "Car" you could store its color in a field named "Color".
Note that a field is also called a member variable or class's data members.

Example:

Public Class Vehicle


Public V_Name As String
Public V_Price As Double
End Class

You can access the field after creating an object (instance).


Dim Car As New Vehicle
Car.V_Name = "Maruti Zen"
Car.V_Price = 100000

 Property : -
Properties are retrieved and set like fields, but are implemented using property Get and property
Set procedures (method), which provide more control on how values are set or returned. It is an easy way to
guarding to the data in your object.

The layer of indirection between the value being stored and the procedures that use this value helps
isolate your data and allows you to validate values before they are assigned or retrieved.
 Set property procedure used to set (assign) the value of a property.
 Get property procedure used to return (get) the value of a property.
 Note that you can make properties write-only with the WriteOnly keyword (and you must omit the
Get method):
 You can make properties read-only with the ReadOnly keyword (and you must omit the Set
method):

Example:
Public Class Vehicle
Private V_No As String
Public Property Vehicl_No() As String
Get
Return V_No
End Get
Set(ByVal value As String)
V_No = value
End Set
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
End Property
End Class

-Now you can access the property after creating an object (instance).
Dim Car As New Vehicle
Car.Vehicl_No = "GJ-15/786"
MsgBox(Car.Vehicl_No)

 Methods : -
Methods represent the object’s built-in procedures. For example, a class named Vehicle may have
methods named Moving and Strat etc. You define methods by adding procedures, either Sub procedures or
functions, to your class.
Example:
Public Class Vehicle
Public Sub move()
MsgBox("Moving")
End Sub
Public Function Stop1() As String
Return "Stoped"
End Function
End Class
Now you can access the method after creating an object (instance).
Dim Car As New Vehicle
Car.move()
MsgBox(Car.Stop1())

 Event: -
Events allow objects to perform actions whenever a specific occurrence takes place. An
example of an event for the "Car" class would be a "Check_Engine" event. Because Microsoft Windows is
an event-driven operating system, events can come from other objects, applications, or user input such as
mouse clicks or key presses.

 Constructors:-
Constructor method executes automatically whenever new object (instance) is created. Constructor is
used to initialize an object.
Constructor is typically declared with Public keyword. To create a constructor for a class, create a
procedure using the Sub New( )……End Sub block anywhere in the class definition.
Example:
Public Class Vehicle
Private V_Color As String

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Public Sub New(ByVal newValue As String)
V_Color = newValue
End Sub
End Class
Now when you create a new object, Constructor method executes automatically
Dim Car As New Vehicle("Blue")

 Destructors: -
The life cycle of an object ends when they leave scope or are set to Nothing and are released
by the .NET framework. Destructor is a method that executes (called by the system) whenever an object
goes out of the scope or destroyed. You can use this method to deallocate resources, disconnect from the
Internet, inform other objects that the current object is going to be destroyed, and more.

In VB.NET, The destructor is written using the Finalize method. Finalize method is called
automatically by the system when an object is destroyed (which means that you should not explicitly call
Finalize yourself).
All the classes in VB.NET implicitly inherit from a class called Object. This class Object defines a
Finalize( ) method. Since the user define class implicitly inherits from Object, we need to use the keyword
Overrides.
Example:
Public Class Vehicle
Protected Overrides Sub Finalize()
MsgBox("Object is now going to be destroyed")
Beep()
End Sub
End Class

Note that you have to use the Overrides keyword with Finalize, because you're actually
overriding the Finalize method built into the Object class

Note: A class can have many overloaded constructors but only one destructor.

 Access Modifier:-
Public, Private, Protected, Friend, or Protected Friend:

 Public— Gives public access, which means there are no restrictions on their accessibility.
 Private— Gives private access, which means they are accessible only from within their class,
including any nested procedures.
 Protected— Gives protected access, which means they are accessible only from within their own
class or from a class derived from that class. Note that you can use Protected only at class level
(which means you can't use it inside a procedure), because you use it to declare members of a class

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Friend— Gives friend access, which means they are accessible from within the program that
contains their declaration, as well as anywhere else in the same assembly. (methods, property, fields,
events are accessible throughout the program in which the class is defined)
 Protected Friend— Gives both protected and friend access, which means they can be used by
code in the same assembly, as well as by code in derived classes.

Advantage of OOP:-
 The primary advantage of Object Oriented Programming is code reuse (reusability). This means that
one need not to create code from scratch; instead, existing codes can be re-used and built upon to
create new codes.
 Object Oriented Programming also offers several other advantages. Users of the objects do not need
to know internal specifications of the object. Objects can also be made to exhibit varying behaviour
under different situations without changing any of the functionality.
 OOP also supports Abstraction, Inheritance, Encapsulation, and Polymorphism.

 Defination: -
Encapsulation, Inheritance, & Polymorphism
Fields, properties, methods, and events are only one half of the object-oriented
programming equation. True object-orient programming requires objects to support three qualities:
encapsulation, inheritance, and polymorphism.
Encapsulation is the process of packaging information in such a manner that relevant
information is made visible & other details of the object is hidden. In other words it is bundling relevant
details of an object into a single unit.
Encapsulation or information hiding refers to the fact that objects hide the detail how
they work. Developers hide the complexity. For example car driver should not bother about car engine.
When you set the text property of the TextBox control, you do not know how the TextBox internally
repaints the character. Another example is caption of the form.
Encapsulation means that a group of related properties, methods, and other members are
treated as a single unit or object. Objects can control how properties are changed and methods are executed.
For example, an object can validate values before allowing property changes. Encapsulation also makes it
easier to change your implementation at a latter date by letting you hide implementation details of your
objects, a practice called data hiding.
Inheritance describes the ability to create new classes based on an existing class. The
new class inherits all the properties and methods and events of the base class, and can be customized with
additional properties and methods. For example, you can create a new class named "Truck" based on the
"Car" class. The "Truck" class inherits the "Color" property from the "Car" class and can have additional
properties such as "FourWheelDrive."

Polymorphism is the ability of an entity to have many forms.Polymorphism means that


you can have multiple classes that can be used interchangeably, even though each class implements the same
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
properties or methods in different ways. Polymorphism is essential to object-oriented programming because
it allows you to use items with the same names, no matter what type of object is in use at the moment. For
example, given a base class of "Car," polymorphism enables the programmer to define different
"StartEngine" methods for any number of derived classes. The "StartEngine" method of a derived class
named "DieselCar" may be completely different from the method with the same name in the base class.
Other procedures or methods can use the "StartEngine" method of the derived classes in exactly the same
way, no matter what type of "Car" object is being used at the time.

 Shared: -
Shared Data Members:
You can use the Shared keyword to create class data members. You can use a class data
member with the name of the class alone, no object needed. No object is needed to access the shared data
members.
For example, say you have a class named Mathematics, and declare a shared variable named Pi:
Public Class Mathematics
Public Shared Pi As Double = 3.1415926535
End Class
Now you can use Pi as a class variable with the Mathematics class directly, no object needed:
integer5 = Mathematics.Pi

The reason variables you declare with the Shared keyword are called shared is because
they're shared over all instances of the class. For example if you have a shared data member named X1 to
the Mathematics class, and each instance(object) of this class(Mathematics) will now see the same value
stored in X1.

Shared Methods:-
When you create a class method, you can use it with the class alone, no object needed.
No object is needed to access the shared methods.
For example: Mathematics class have Shared method name as Add. Then you can use
the shared method without crating an object. Only you have to use ClassName.SharedMethodName
(Mathematics.Add)

Example:
Public Class Mathematics
Shared Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
End Class
In program, you can use the shared method without crating an object as follows.
Mathematics.Add(776,10)

Also you can create Shared Property & Event.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Overloading Methods, Properties, Constructor:
In OOP, methods and properties can be overloaded, which means that you can
define a method or property multiple times with different argument lists.
Overloading is the process of declaring methods (Sub procedure or Function
procedure), or property or constructor of a class having the same name but different signatures. The
signature of the method contains the name of the method, the numbers of arguments & types of arguments.
In VB.NET, (1) Functions (2) Procedure (3) Property & (4) Constructors within a class can be
overloaded.
Example:
Public Class Maths
Function Area(ByVal L As Integer) As Integer
Return L * L
End Function
Function Area(ByVal B As Integer, ByVal H As Integer) As Integer
Return 1 / 2 * B * H
End Function
End Class
Now uou can access the overloaded Area method by passing different arguments.

Dim Maths1 As New Maths


MsgBox("Area of Square is = " & Maths1.Area(10))
MsgBox("Area of Triange is = " & Maths1.Area(10, 5))

Inheritance:-
Inheritance is the process use to derive one class from another.Inheritance is the process of creating
classes based on existing classes. Existing class is called as base class or parent class. New class is called as
the derived class or child class.
Inheritance is based on the principle of reusability (reusability of code). Instead of creating a class
from scratch, we can add new methods, properties & events to the existing classes, thus saving time &
effort.
This is more useful than it may sound, because Visual Basic comes with thousands of built-in base
classes for you to create derived classes from and then customize. We're already familiar with this process
from our work with Windows forms, of course, because we derive our forms from
System.Windows.Forms.Form and then customize them with buttons and event handlers, like this:
Inherits statement is used to derived a new class from the existing class. Derived classes inherit,
and can extend, the properties, methods, events, fields, and constants defined in the base class

Class DerivedClassName
Inherits BaseClassName
Example:
Public Class Building
Public Address As String
Public Floors As Integer
End Class
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Public Class Apartment
Inherits Building
Public name As String
End Class
Now you can access the members of the class as follows
Dim Apt1 As New Apartment
Apt1.name = "OM"
Apt1.Address = "Goa"
Apt1.Floors = 3

 Overridden: Overridden properties and methods are used to replace an inherited property or
method. When you override a member from a base class, you replace it. Overridden members must
accept the same data type and number of arguments.

 Overloaded: Overloaded members provide different versions of a property or method that


have the same name, but that accept different number of parameters (or parameters of different
types).

 Overriding Base Class Members:


When you inherit from a base class, you can override (replace) or (overwriting) base
class members in the derived class.
Overriding is the process of overwriting or replacing the methods or properties of a
base class in a derived class. In case of method overriding, the return type, name & arguments of the
method in the derived class must be the same as that of the method being overridden. When an object of the
derived class invokes the overridden method, it will be the derived class implementation that will be called.
The base class method must be marked with the keyword Overridable and the derived class method
must be marked with the keyword Overrides.

The following modifiers are used to control how properties and methods are overridden:

 Overridable— Allows a property or method in a class to be overridden.


 Overrides— Overrides an Overridable property or method.
 NotOverridable— Prevents a property or method from being overridden. Note that public
methods are NotOverridable by default.
 MustOverride— Requires that a derived class override the property or method. MustOverride
methods must be declared in MustInherit classes.

Example:

Public Class MyBaseClass


Public Overridable Sub Test(ByVal X As Integer, ByVal Y As Integer)
MsgBox(X + Y)
End Sub
End Class

Public Class MyDeriveClass


Inherits MyBaseClass

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Public Overrides Sub Test(ByVal X As Integer, ByVal Y As Integer)
MsgBox(X * Y)
End Sub
End Class
Now you can access the Test method as follows
Dim BaseObj As New MyBaseClass
BaseObj.Test(2, 5) 'Answer will be 7

Dim DeriObj As New MyDeriveClass


DeriObj.Test(2, 5) 'Answer will be 10

 Using the MustInherit Keyword (Creating Abstract Class)


Abstract Base Class:
An abstract class is a class that cannot be instantiated. In other words, an abstract class cannot be
used to create objects. It is generally used as a template to derive other classes. An abstract class typically
has abstract methods which are only method declarations without any implementation.
In VB.NET all classes are inheritable. The MustInherit keyword makes the base class an abstract
class. You can not create an object of abstract base class.
Following example defining an abstract base class, that has one abstract method & one non- abstract
method.

Public MustInherit Class AbsBaseClass

Public Sub Test()


MsgBox("Abstract Base Class")
End Sub

MustOverride Sub AnothrTest()


End Class

Public Class child


Inherits AbsBaseClass
Public Overrides Sub AnothrTest()
MsgBox("Implementing abstract base method")
End Sub
End Class
Now you can access as follows

Dim childobj As New child


childobj.Test()
childobj.AnothrTest()

 Final Class: -
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Final class in VB.NET is marked with the NotInheritable keyword. Final class can not
have derived class but can be used to create objects. So you can not inherit from this class. Means this is the
class from which no further inheritance is allowed.
Example:-
Public NotInheritable Class MyFinalClass
Public Sub Test()
MsgBox("Final Class")
End Sub
End Class

Public Class child


Inherits MyFinalClass ‘  It will result compil error
End Class

 When you inherits final class, It will result compil error. Because of NotInheritable keyword,

Inheritance Modifiers:-
By default, all classes can serve as base classes in Visual Basic .NET. However, you can use two
class-level modifiers, called inheritance modifiers, to modify that behavior:

 NotInheritable— Prevents a class being used as a base class.


 MustInherit— Indicates that the class is intended for use as a base class only.

Shadowed:-
Any type can shadow any other type. For example, you can declare a property that shadows an
inherited method with the same name. Shadowed members cannot be inherited. Shadows keyword can not
be used with the Overloads keyword.

You can hide a variable by shadowing it, that is, by redefining it with a variable of the same name. If the
variable you want to hide is defined at class level, you can shadow it through inheritance by redeclaring it
with the Shadows keyword in a derived class

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
For example, imagine that a module defines a public variable named Data, and a procedure
inside the module declares a local variable also named Data. When you use the name Data in the procedure,
you use the local variable, but references to Data outside the procedure use the public variable. Here, the
procedure-level variable Data shadows the module-level variable Data.

Class Class1
Public Pi As Double = 3.1415926535
End Class

Class Class2
Inherits Class1

Public Shadows ReadOnly Property Pi() As Double


Get
Return 3.1415926535
End Get
End Property
End Class

 In above example if you do not write Shadows keword then following error will occurs.Property “Pi”
conflicts with the variable “Pi” in the base class “class1” & should be declare “Shadows”

MyBase Keyword:-
MyBase is commonly used to access base class members that are overridden or shadowed
in a derived class. In particular, MyBase.New is used to explicitly call a base class constructor from a
derived class constructor.

You can use the MyBase keyword to access methods in a base class when overriding
methods in a derived class. For example, suppose you are designing a derived class that overrides a method
inherited from the base class; in this case, the overridden method can call the original method in the base
class using MyBase.

Note that MyBase is a keyword and not an object, so you can't assign it to a variable. And,
It can be used to access only Public & Protected members of the base class. You cab not use MyBase in
modules.

Example:
Public Class Animal

Public Overridable Sub Eats()


MsgBox("Eats Foods Base Class Eats Method”)
End Sub
End Class

Public Class Cow


Inherits Animal
Public Overrides Sub Eats()

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
MsgBox("Eats Grass Derived Eats Method ")
End Sub

Public Sub Eating()


MyBase.Eats()
MsgBox("Is a herbivourous animal")
End Sub

End Class

‘Creates Object as follows


Dim C As New Cow()
C.Eating()
C.Eats()

‘Output
Eats Foods Base Class Eats Method
Is a herbivourous animal
Eats Grass Derived Eats Method

The code in above example creates a base class animal that defines one
Overridabel method Eats( ). This Eats( ) method is later Overrides by a child class cow.

Derived class has also another method Eating( ), in that we want to access the
original method Eat( ) of the base class, and not the Overrides method of the child class. To indicate that it
is the base class method we wish to invoke, We have to invoke wite the MyBase keyword.

 MyClass Keyword:-
Provides a way to refer to the current class instance members without them being
replaced by any derived class overrides.

The MyClass keyword allows you to call an Overridable method implemented in


your class and make sure that implementation of the method in this class is called rather than an overridden
method in a derived class.

MyClass keyword works opposite to the way in which MyBase keyword works.
Assume that, If we wish to call the base class version of the method (an overridable method), instead of the
derived class version, We must use the MyClass keyword.

The MyClass keyword lets you call an overridable method in your class (while
making sure that implementation of the method in your class is called) instead of an overridden version of
the method.

Public Class Animal


Public Overridable Sub Eats()
MsgBox("Animal Eats Food")
End Sub
Public Sub EatingHabits()
MsgBox("Calling method directly")
Eats()
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
MsgBox("Calling method using MyClass")
MyClass.Eats()
End Sub
End Class

Public Class Cow


Inherits Animal
Public Overrides Sub Eats()
MsgBox("Cow Eats Grass")
End Sub
End Class

‘Creates Object as follows


Dim C As New Cow
C.Eats()
C.EatingHabits()

‘Output
Cow Eats Grass
Calling method directly
Cow Eats Grass
Calling method using MyClass
Animal Eats Food

 Creating Interfaces: -
Although a class can inherit only from one base class, it can implement multiple interfaces.
As in Java, an interface is a specification for a set of class members—not an
implementation, just a specification.

In this example, I'll define an interface named person and implement that
interface in a class named employee to show that implementing interfaces is a little like inheriting from a
base class. First, I create the person interface with the Interface statement, indicating that this interface
consists of two methods, SetName and GetName, which set and get the name of a person:

Public Interface person


Sub SetName(ByVal PersonName As String)
Function GetName() As String
End Interface

Notice that there's no implementation of these methods here, just their declarations.
As mentioned above, all an interface does is specify members; when you implement the interface, you must
implement all the members yourself. You do that with the Implements keyword (which must come after
any Inherits statements and before any Dim statements in a class). Here's how I implement the person
interface in a class named employee; note that I specify which class method implements which interface
method using the Implements keyword:

Public Class employee


Implements person
Dim Name As String
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Sub SetName(ByVal PersonName As String) Implements person.SetName
Name = PersonName
End Sub

Function GetName() As String Implements person.GetName


Return Name
End Function
End Class

Now I can create a new object of the employee class named Edward:

Dim Edward As New employee ()


Edward.SetName ("Edward")
TextBox1.Text = "You created” & Edward.GetName ()

 Using Multiple Interfaces :-


Visual Basic does not support multiple inheritance, where you inherit from multiple
base classes at the same time. Like Java, however, Visual Basic lets you implement multiple interfaces at the
same time, which is a dressed-down version of multiple inheritance.

Early Binding:-
An object is early bound when it is assigned to a variable declared to be of a specific object
type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an
application executes.

Late Binding:-
By contrast, an object is late bound when it is assigned to a variable declared to be of type
Object. Objects of this type can hold references to any object, but lack many of the advantages of early-
bound objects.

Advantages of Early Binding:-


You should use early-bound objects whenever possible, because they allow the
compiler to make important optimizations that yield more efficient applications.

Early-bound objects are significantly faster than late-bound objects and make your
code easier to read and maintain by stating exactly what kind of objects are being used. Another advantage
to early binding is that it enables useful features such as automatic code completion and Dynamic Help
because the Visual Studio integrated development environment (IDE) can determine exactly what type of
object you are working with as you edit the code.

Early binding reduces the number and severity of run-time errors because it allows
the compiler to report errors when a program is compiled.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Creating Structures: -
Traditionally, structures were used to let you create your own complex data types.
For example, if you wanted to store both an employee's ID value (an integer) and a employee's name (a
string) in one variable, you could create a new structure named, say, Employee, like this:

Public Structure Employee


Public Name As String
Public ID As Integer
End Structure

This creates a new data type. Now you can declare a variable of this new type, and
access the data fields in it, like this:

Dim employee As Employee


employee.Name = "Cary Grant"
employee.ID = 101

Now, however, structures are much like classes and can support events,
methods, and properties as well as fields.

 Because you cannot inherit from a structure, structures should be used only for objects that do not
need to be extended. Use structures when the object you wish to create has a small instance size, and
take into account the performance characteristics of classes versus structures. (Structures are not
inheritable; classes are).
 All structure elements are Public by default; class variables and constants are Private by default,
while other class members are Public by default.
 A structure does not require a constructor; a class does.

Creating Modules:-
Traditionally in Visual Basic, you used modules to divide your code up into smaller units,
because modules were designed primarily to hold code

Here's an example

Module Module1
Sub Main()
System.Console.WriteLine("Hello from Visual Basic")
System.Console.WriteLine("Press Enter to continue...")
System.Console.ReadLine()
End Sub
End Module

However, as mentioned earlier, modules can now hold methods, fields, properties,
and events, just as classes can.

Classes and Modules:-


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
These elements have many similarities, but there are some important differences as well.
The main difference between classes and modules is that classes can be
instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's
data, when one part of your program changes a public variable in a standard module, any other part of the
Program gets the same value if it then reads that variable. In contrast, object data exists separately for each
instantiated object. Another difference is that unlike standard modules, classes can implement interfaces.

 Terminology. Previous versions of Visual Basic recognize two types of modules: class modules
(.cls files) and standard modules (.bas files). The current version calls these classes and modules,
respectively.
 Shared Members. You can control whether a member of a class is a shared or instance member.
 Object Orientation. Classes are object-oriented, but modules are not. So only classes can be
instantiated as objects..

Creating Class Libraries:-


When you've got a large number of classes to handle, you can store them in a class library
and compile them into a DLL file, which can be used across multiple projects if you wish.

To make this class library available to other projects, you compile it into a DLL (dynamic
link library) file using the Build|Build ClassLibraries menu item which creates, in this case,
ClassLibraries.dll.

To use the classes in ClassLibraries.dll in the new project, click the Project|Add
Reference menu item to open the Add Reference dialog box. Click the Projects tab, then double click the
ClassLibraries item to make it appear in the Selected Components box, then click OK.

Creating Namespaces: -
When you're creating a large number of classes, it can be helpful to divide them up into their own
namespaces to help organize things. We already know about namespaces; as the name implies, you use them
to create separate spaces so that names can't conflict with other names already declared.

Namespaces are used to hold collection of related classes. It also helps to avoid clashes between
class names.

To create your own namespace, you can use the Namespace statement:

Namespace {name | name.name}


componenttypes
End Namespace

Here are the parts of this statement:

name—Required. A unique name that identifies the namespace.

componenttypes—Required. Elements that make up the namespace. These include enumerations,


structures, interfaces, classes, delegates, and so on.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Note that namespaces are always public, which means that the declaration of a namespace cannot
include any access modifiers. (However, the components inside the namespace may have public or friend
access; the default access is friend.)

Here's an example that declares two namespaces, one inside another:


Namespace Secret ' Declares a namespace named Secret.
Namespace TopSecret ' Declares a namespace named TopSecret in Secret.

Class Documents ' Declares the class Secret.TopSecret.Documents



End Class
End Namespace
End Namespace

The System Namespaces:-


You can't build a VB 2005 (.NET) application without using classes from
the .NET System namespace. When you want to use a Windows form, for example, you must use the
System.Windows.Forms.Form class. A button in a Windows form comes from the
System.Windows.Forms.Button class, and so on. There are many such classes, organized into various
namespaces like System.Windows.Forms. Here's an overview of some of those namespaces:

Namespace Contain
System : Includes essential classes and base classes that define commonly used data types,
events and event handlers, interfaces, attributes, exceptions, and so on.
System.Collections: Includes interfaces and classes that define various collections of objects,
including such collections as lists, queues, arrays, hash tables, and dictionaries.
System.Data: Classes that constitute the ADO.NET architecture for access & management of
data & data sources.
System.Net: Functionality for sending & receiving data over a network using almost all the
available network protocol.
System.Windows.Forms: Classes for creating Windows based application.
For example: Me.LayoutMdi (MdiLayout.Cascade)

 Computer Application:-
Examples of computer application are Inventory Management System, Payroll Management System,
Library Management System, School Management System, AHMS (Automatic Hospital Management
System), HRMS (Human Research Management System), Banking Management System, Reservation
System etc.
Any computer application divides into two parts.
1) Program.
2) User Interface.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Programs:-
Computer need clear cut instructions to tell them what to do? When to do? And how to do?
Progarm is a set of instructions that is used to carry out specific task.

 User Interface:-
Users interact with a computer application via user interface. Windows program use controls to
provide easy and pleasant user interface. Good user interface will be easy to learn, easy to use, attractive. It
means more users friendly.
(1) CUI: In CUI text was the medium of information exchange. Example of CUI is DOS in
which users have to remember lots of commands at DOS prompt. User cannot run more then
one application at a time.
(2) GUI: In GUI graphics is medium of information exchange. Interface that use graphics,
(graphical objects like menu, button, textbox, toolbar, radio button, window etc.) is known as
GUI.

Example of GUI is Windows. GUI application is easy to use and easy to learn and easy to
understand. That means it is more user friendly. It reduces the operator workload.

 Advantages of Visual Programming:-


1) Ready to use components (Objects / Controls). Programmer need not to write code to display
require components (Objects OR controls).
2) The components (objects or controls) can be move, resize rename & delete if required.
3) There is no restriction on the no. of controls that can be placed on the form. All components have
ability to recognize events for example button known when it has been clicked.
Example of visual programming tools (GUI Tools) are VB, PB (Power Builder), D2K (Developer 2000).

 Disadvantages of Visual Programming:-


1) Highly graphical on nature, therefore it requires more memories.
2) Visual development requires the computer of higher configuration. That is more RAM, Higher
processor.
3) It is used only with GUI operating system such as Windows.

 Property :-
Characteristics of Control (Object) are called as property. Example is Name, BackColor, ForeColor,
Visible, Enable, Font etc.
VB assign default property to every new control when you place on a form, you can change default
property of a control,
(1) At design time (using property window) OR (2) At run time (through coding)
 Method:-
Method is a predefine function associated with controls (objects). OR
Method is a code that is built into interface components (control).
It hides the information detail. (Encapuslation)
Examples of methods are SetBound, SendToBack, BringToFront, Copy, Cut, Paste, SelectAll etc

 Event:-
Event are response that are triggered (fired or execute or run), when user interact with control.
OR
An event is an action which you can respond to, or "handle," in code. Events can be generated by a
user action, such as clicking the mouse or pressing a key; by program code; or by the system.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Examples of events are Click, DoubleClick, KeyPress, KeyDown, KeyUp, MouseDown,
MouseEnter, MouseHover, MouseLeave, MouseUp, MouseMove, MouseWheel, TextChanged etc
VB. NET is also colled as a event driven programming language, because code is executed with
response to event.
Visual Basic controls are based on classes provided by the .NET Framework.
Windows controls are bases on Control class. The Control class is in the System.Windows.Forms
namespace.

(1) Label Control:


Windows Forms Label controls are used to display text or images that cannot be edited by the
user.
Label controls are typically used to provide descriptive text for a control. For example, you can use a
Label to add descriptive text for a TextBox control to inform the user about the type of data expected in the
control. To provide a description of what a certain control will do if clicked, in short it is used to label other
parts of your application. For example, you can use labels to add descriptive captions to text boxes, list
boxes, combo boxes, and so on.
Labels are based directly on the Control class. (Inheritance Hierarchy)
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.Label

Namespace: System.Windows.Forms

 Property of Label Control: -


(1) Name: - Gets or sets the name of the control. It represents the name of the control. It is used for
identification.
(2) Text: - Gets or sets the current text of the control. It is the text that is displayed within the control.
For ex. Lable1.Text = “OMSHIVSAI”
(3) BackColor: - Gets or sets the background color for the control.
For Ex. Label1.BackColor = Color.Purple
(4) ForeColor: - Gets or sets the foreground color for the control.
For Ex. Label1.ForeColor = Color.Red
(5) AutoSize: - Gets or sets a value indicating whether the control is automatically resized to display its
entire contents. When this property is set to true, the Label adjusts its width to display its entire
contents. This property is typically set to true when you use a Label control to display various lengths
of text.
It will automatically resize the control to the height and width of the control.
For Ex. Label1.AutoSize = True
(6) Visible: - Gets or sets a value indicating whether the control is visible on the form or not. If you set it
to false, the control will not be display (visible).
For Ex. Label1.Visible = False
(7) Enable: - Gets or sets a value indicating whether the user can use the control or not (whether the
control can respond to user interaction or not). With the Enabled property, you can enable or disable
controls at run time or at design time. If it is set to false, the control cannot get user input, means it
become gray.
For Ex. Button1.Enable = False

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(8) Left: - Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its
container's client area.
The Left property value is equivalent to the Point.X property of the Location property value of the control.
Changes made to the Width and Left property values cause the Right property value of the control to
change.
(9) Right: - Gets the distance, in pixels, between the right edge of the control and the left edge of its
container's client area.
The value of the Right property is equal to the sum of the Left property value and the Width property value.
The Right property is read-only. You can change this property value indirectly by changing the value of the
Left or Width properties or calling the SetBounds, SetBoundsCore, UpdateBounds, or SetClientSizeCore
methods.
(10) Top: - Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its
container's client area.
The Top property value is equivalent to the Point.Y property of the Location property value of the control.
Changes made to the Height and Top property values cause the Bottom property value of the control to
change.
(11) Bottom: - Gets the distance, in pixels, between the bottom edge of the control and the top edge of its
container's client area.
The value of this property is equal to the sum of the Top property value, and the Height property value.
The Bottom property is a read-only property. You can manipulate this property value by changing the value
of the Top or Height properties or calling the SetBounds, SetBoundsCore, UpdateBounds, or
SetClientSizeCore methods.
(12) Margin: - Gets or sets the space between controls.A padding representing the space between
controls.
(13) BorderStyle: - Gets or sets the border style (border type) for the control. You can use this property
to add a border to the control.
Fixed3D : A three-dimensional border. (2)
FixedSingle : A single-line border. (1)
None : No border. (The default value is None) (0)
For Ex. Label1.BorderStyle = BorderStyle.Fixed3D
(14) TextAlign: - Gets or sets the alignment of text in the label control.
Gets or sets how text is aligned in a label control.
(TopCenter, TopLeft, TopRight, MiddleCenter, MiddleLeft, MiddleRight, BottomCenter, BottomLeft,
BottomRight)
System.Drawing.ContentAlignment Enumeration
Specifies alignment of content on the drawing surface.

For Ex.:- Label1.TextAlign = ContentAlignment.BottomCenter


OR
Label1.TextAlign = 512
(15) Size: - Gets or sets the height and width of the control in pixels.
For Ex.:- Label1.Size = New System.Drawing.Size (200, 500)
OR Label1.Size = New Size (200, 500)
(16) Location: - Gets or sets the coordinates of the upper-left corner of the control relative to the upper-
left corner of its container.
For Ex. Label1.Location = New Point(100, 100)
(17) Cursor: - Gets or sets the cursor that is displayed when the mouse pointer is over the control.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
To temporarily change the mouse cursor for all controls on your application set the Cursor.Current property.
For Ex: - Label1.Cursor=Cursors.Hand
(18) FlatStyle: - Gets or sets the flat style appearance of the label control.
Flat : The control appears flat.
Popup : A control appears flat until the mouse pointer moves over it, at which point it appears
Three-dimensional.
Standard : The control appears three-dimensional. The default value is Standard.
System : The appearance of the control is determined by the user's operating system.
(19) UseMnemonic: - If it is set to True, then the first character preceded by an ampersand (&) (defined
in the text property of the label) will be use as a label’s mnemonic key. By pressing ALT + the mnemonic
character sets the focus to the control that follows the Label in the tab order. By default it is set to True.
(20) Image: - Gets or sets the image that is displayed on a Label. The default is a null reference (Nothing
in Visual Basic). You can display image at design time (via property window) & run time (via coding).
At run time FromFile method of Image class is used to display image on a label conrol.
For Ex: - Label1.Image = Image.FromFile ("C:\SAI.JPG")
(21) ImageAlign: - Gets or sets the alignment of an image that is displayed in the control.
(TopCenter, TopLeft, TopRight, MiddleCenter, MiddleLeft, MiddleRight, BottomCenter, BottomLeft,
BottomRight)
Label1.ImageAlign=ContentAlignment.TopLeft
(22) Locked: - This property is new in the .NET Framework version 2.0.
Gets or sets a value indicating whether the Label Control can be moved or resized. If it is set to true, then
Label Control can not be moved or resized. The default is false.
(23) Font: - Gets or sets the font of the text displayed by the control.
For ex: -
Dim Fobj AS New System.Drawing.Font ("Arial", 21, FontStyle.Bold)
Label1.Font = Fobj
OR
For ex: -
Label1.Font = New System.Drawing.Font ("Arial", 21, FontStyle.Bold)

 Method of Label Control: -


(1) SetBound: - Sets the bounds of the control to the specified location and size.
SetBound(x, y, Width, Height)
Parameters:-
X The new Left property value of the control.
Y The new Top property value of the control.
Width The new Width property value of the control.
Height The new Height property value of the control.

For Ex: - Label1.SetBounds (400, 400, 100, 100)


(2) BringToFront: - Brings the control to the front of the z-order.
For Ex: - Label1.BringToFront ()
(3) SendToBack: - Sends the control to the back of the z-order.
For Ex: - Label1.SendToBack ()

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Events of Label Control : -
(1) Click: - Click event is fire (raised or event handler is executed or triggered) when control is click.
For example:-
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Me.Text = “|| HARI OM SHRI JAY GANESHAY NAMAHA: OMSHIVSAI ||”
End Sub
Two arguments are common to all events.
ByVal sender As System.Object and ByVal e As System.EventArgs
 The first argument (parameter), Sender which passes information about the object. (Provides a
reference to the object that raised the event).
Where sender used to find out, which control fires the event. (Name of the control that fires the
event. For example Console.WriteLine (Sender.ToString)  Button1
Where sender argument also used to find out, the type of the control that fires the event. For example
Console.WriteLine (Sender.GetType)  Button
 The second argument (parameter), e which passes information about the action that invokes the
event. By referencing the object's properties (and, sometimes, its methods), you can obtain information such
as the location of the mouse for mouse events, or data being transferred in drag-and-drop events.
Example:-
Private Sub Button1_Click (ByVal sender As Object, ByVal e AS _
System.EventArgs) Handles Button1.Click, Button2.Click
sender.Text = "Help me!"
End Sub
In the above example, notice that the event declaration has a Handles clause that defines which events will
be handled. Handles allows multiple events to be handled by one event handler. In this case, the Click
event for both the Button1 and Button2 objects.
(2) DoubleClick: - Occurs (Fires or Executes) when the control is double-clicked.
(3) MouseDown: -Occurs when the mouse pointer is over the control and a mouse button is pressed.
(Namespace: System.Windows.Forms)
Mouse events occur in the following order:
1. MouseEnter
2. MouseMove
3. MouseHover / MouseDown / MouseWheel
4. MouseUp
5. MouseLeave
Example 1:
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
TextBox1.Text = "Mouse down at : " & e.X & " : " & e.Y
End If
End Sub

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Example 2:
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
Me.Text = "Mouse moved : " & e.X & " : " & e.Y
End Sub

 Properties of the MouseEventArgs Object:-


Button Gets (Indicates) which mouse button was pressed.
Clicks Gets the number of times the mouse button was pressed and released.
Delta Gets a signed count of the number of detents the mouse wheel has rotated. A detent is one
Notch of the mouse wheel.
Location Gets the location of the mouse during the generating mouse event.
X Gets the x-coordinate of the mouse during the generating mouse event. (The x-coordinate of
the mouse click).
Y Gets the y-coordinate of the mouse during the generating mouse event. (The y-coordinate of
the mouse click).

 MouseEventArgs.Button Property holds one of these members of


useButtons enumeration: -

Left The left mouse button was pressed.


Middle The middle mouse button was pressed.
None No mouse button was pressed.
Right The right mouse button was pressed.
XButton1 The first XButton was pressed.
XButton2 The second XButton was pressed.
With Windows 2000, Microsoft is introducing support for the Microsoft IntelliMouse
Explorer, which is a mouse with five buttons. The two new mouse buttons (XBUTTON1 and XBUTTON2)
provide backward/forward navigation.
(4) MouseEnter: - Occurs when the mouse pointer enters the control.
(5) MouseHover: - Occurs when the mouse pointer hovers over the control.
(6) MouseLeave: - Occurs when the mouse pointer leaves the control.
(7) MouseMove: - Occurs when the mouse pointer is moved over the control.
(8) MouseUp: - Occurs when the mouse pointer is over the control and a mouse button is released.
(9) MouseWheel: - Occurs when the mouse wheel moves, while the control has focus.
(10) TextChanged: - Occurs (Fires or Executes) when the Text property value has changed.
(11) Paint: -Occurs when the control is redrawn or updated.
(12) MouseClick: -
Note: This event is new in the .NET Framework version 2.0.
Occurs when the control is clicked by the mouse.

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


System.Windows.Forms.MouseEventArgs) Handles Label1.MouseClick
End Sub
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(13) MouseDoubleClick: -
Note: This event is new in the .NET Framework version 2.0.
Occurs when the control is double clicked by the mouse.

(2) TextBox Control: -


TextBox control is used to get input from the user or display text to the user. An instance (object) of
the “TextBox” class is created when a TextBox control is added to the form. Txt boxes can be multiline,
have scroll bars, be read only, and have many other attributes. The text displayed by the control is contained
in the Text property. 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
TextBox control sometime also called as edit control. It is used to accept user input. The main
difference between textbox control & label control is that, user can modify the text inside the textbox, but
user can not modify the text in a label control.

 Property :-
(1)Name (2)Text (3)BackColor (4)ForeColor (5)AuotSize (6)Visible (7)Enable (8)Left (9)Right
(10)Top (11) Bottom (12)Margin (13)BorderStyle
(14) TextAlign :- Gets or sets how text is aligned in a TextBox control.
Gets or sets how text is aligned in a textbox control.
This HorizontalAlignment enumeration is used to align the text to the left, right, or in the center of a control
element.
TextBox1.TextAlign = HorizontalAlignment.Center
(15) Size (16) Location (17) Cursor
(18) MultiLine: - Gets or sets a value indicating whether this is a multiline TextBox control. True if the
control is a multiline TextBox control; otherwise, false.
By default, you can enter up to 2048 characters (2KB) in a text box (MultiLine property is set
to False). If you set the Multiline property to true, you can enter up to 32 KB of text.
(19) MaxLength: - Gets or sets the maximum number of characters the user can type or paste into the
text box control. The default is 32767.
(20) HideSelection: - Gets or sets a value indicating whether the selected text in the text box control
remains highlighted when the control loses focus.
If you set this property to True, then the selected text does not appear highlighted when the
text box control loses focus. (The default is true).
You can use this property to keep text highlighted in a text box control while another form or
a dialog box has focus, such as a spelling checker dialog box.
(21) Lines: - Gets or sets the lines of text in a text box control. Lines is a string array where each
elements, holds a line of text.
You can access individual lines of text through Lines property.
TextBox1.Lines (0), TextBox1.Lines (1), TextBox1.Lines (2), TextBox1.Lines (3)
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(22) PasswordChar: - Gets or sets the character used to mask characters of a password in a single-line
TextBox control.
If the Multiline property is set to true, setting the PasswordChar property has no visual effect. When
the PasswordChar property is set to true, cut, copy, and paste actions in the control using the keyboard
cannot be performed, regardless of whether the Multiline property is set to true or false.

(23) CharacterCasing:-Gets or sets whether the TextBox control modifies the case of characters as
they are typed. The default is CharacterCasing.Normal Followings are the CharacterCasing enumeration
values.

Lower Converts all characters to lowercase.


Normal The case of characters is left unchanged.
Upper Converts all characters to uppercase.

For ex: ' Change all text entered to be lowercase.


TextBox1.CharacterCasing = CharacterCasing.Lower

(24) ReadOnly: - Gets or sets a value indicating whether text in the text box is read-only. When this
property is set to true, the contents of the control cannot be changed by the user at runtime (it becomes read
only), but user can still view the ToolTips, user can copy the content of the textbox and also navigate the
content using the cursor.
(25) Locked: -As above, Same as Label Control.
(26) ScrollBars: - Gets or sets which scroll bars should appear in a multiline TextBox control.One of the
ScrollBars enumeration values.
None (By default), Horizontal, Vertical or Both
For example, at run time you can set as follows:
TextBox1.ScrollBars = ScrollBars.Vertical

(27) SelectedText: - (Only available at run time, Dynamic property) : Gets or sets a value indicating
the currently selected text in the control. If no text is currently selected in the text box, this property returns a
zero-length string.
(28) SelectionLength: - (Only available at run time, Dynamic property) : Gets or sets the number of
characters selected in the text box.
(29) SelectionStart: - (Only available at run time, Dynamic property) : Gets or sets the starting point
of text selected in the text box. If no text is selected in the control, this property indicates the insertion point
for new text.
(30) TextLength: - Gets the length of text in the control. It is used to get The number of characters
contained in the text of the control.
For ex.1 MsgBox (TextBox1.TextLength)

Example 2 Dim Strlen As Integer


Strlen = TextBox1.TextLength
(31) WordWrap: -Indicates whether a multiline text box control automatically wraps words to the
beginning of the next line when necessary.
If this property is set to true, horizontal scroll bars are not displayed regardless of the ScrollBars property
setting. (Default is True)

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(32) TabIndex: - Gets or sets the tab order of the control within its container.It are the no that will reflect
the order when user press tab key. A tab index can consist of any valid integer greater than or equal to zero.
If more than one control on the same parent control has the same tab index, the z-order of the controls
determines the order to cycle through the controls.
For a control to be included in the tab order, its TabStop property must be set to true.
(33) TabStop: - Gets or sets a value indicating whether the user can give the focus to this control using
the TAB key. If it is set to False, than control will not get focusthrough tab key. The default is True.
(34) AcceptReturn: - Gets or sets a value indicating whether pressing ENTER in a multiline TextBox
control creates a new line of text in the control or activates the default button (OK button) on the form.
If you set this property to True, ENTER key creates a new line of text in a multiline version of the
control. If you set this property to False, ENTER key activates the default button for the form & user must
press CTRL+ENTER to create a new line in a multiline TextBox control. The default is false.
(35) AcceptTab: - By default (False), so user can move the next controlwith the tab key. If you set to
True, you can insert a tab charater in the textbox control & move to next control by pressing control + Tab.
(36) Font: - (Same as Label control)

 Method of TextBox Control :-

(1) SetBound (2) BringToFront (3) SendToBack


(4) AppendText: - Appends text to the current text of a text box.
You can use this method to add text to the existing text in the TextBox control instead of
using the concatenation operator (+) to concatenate text to the Text property. It is much faster than its
equivalent statement. It works faster when content of text is more.
For ex.:- TextBox1.AppendText (“OM”)
(5) Clear: - Clears all text from the text box control. You can use this method to clear the contents of the
control instead of assigning the Text property an empty string.
For ex: - TextBox1.Clear ()
Or TextBox1.Text = “”
(6) Copy: - This method Copies the selected text from the TextBox control to the Clipboard.
For ex:-
‘Ensure that text is selected in the text box.
If TextBox1.SelectionLength > 0 Then
'Copy the selected text to the Clipboard.
TextBox1.Copy ()
End If
(7) Cut: - This method removes (Moves) the selected text box from the TextBox control to the Clipboard.
For ex:-
'Ensure that text is currently selected in the text box.
If TextBox1.SelectedText <> "" Then
'Cut the selected text from the control and paste it into the Clipboard.
TextBox1.Cut ()
End If

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(8) Paste: - This method replaces the selected text in the TextBox with the text from the Clipboard.
TextBox1.Paste ()
(9) SelectAll: - This method is used to Selects all text in the text box.

 Event of TextBox Control: -


(1) Click (2) DoubleClick (3) MouseDown (4) MouseEnter
(5) MouseHover (6) MouseLeave (7) MouseMove (8) MouseUp
(9) MouseWheel (10) MouseClick (11) MouseDoubleClick
(12) TextChanged: - This is the default event of the Textbox control. It is triggered when the text in the
TextBox is changed.

(13) ReadOnlyChanged: - It is triggered when the value of the ReadOnly property is changed.
(14) MultilineChanged: - It is triggered when the value of the Multiline property is changed.
(15) KeyPress: -Occurs when a key is pressed while the control has focus. KeyPress event occurs every
time a key is pressed.
Key events occur in the following order:
1. KeyDown
2. KeyPress
3. KeyUp
With each KeyPress event, it returns e argument of type KeyPressEventArgs.
KeyPressEventArgs have two propertry (KeyChar & Handled).
The KeyChar property of the e arguments returns the key that was pressed. (Returns the character
corresponding to the key pressed).
Set Handled property to true to cancel the KeyPress event.
Use the KeyChar property to sample keystrokes at run time and to modify keystrokes under special
run-time circumstances. For example,
You can use KeyChar to disable non-numeric keypresses when the user enters a ZIP code, change all
alphabetical keypresses to uppercase in a data entry field, or monitor the keyboard or other key input device
for specific key combinations.
 You can get or set the following keys: (KeyChar)
a-z, A-Z. , CTRL, Punctuation marks, Number keys, both across the top of the keyboard and on the
numeric keypad, ENTER.
 You cannot get or set the following keys: (KeyChar)
The TAB key, INSERT and DELETE, HOME, END, PAGE UP and PAGE DOWN,
F1-F12. (All Function Keys), ALT, Arrow keys.

'To allow only alphabets (A to Z or a to z or backspace(8) or spacebar(32) or enter(13)


Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or (Asc(e.KeyChar) >= 97 And
Asc(e.KeyChar) <= 122) Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 32 Or
Asc(e.KeyChar) = 13 Then
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
e.Handled = False
Else
e.Handled = True
End If
End Sub

Example: 2
' To allow only NUMBERS ( 0 to 9) or Backspace(8)
Private Sub TextBox6_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox6.KeyPress
If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or Asc(e.KeyChar) = 8 Then
e.Handled = False
Else
e.Handled = True
End If
End Sub

(16) KeyDown: (17) KeyUp: KeyDown event occurs when a key is pressed while the control has
focus. KeyUp event occurs when a key is released while the control has focus. (The KeyDown event occurs
when the user presses any key. The KeyUp event occurs when the user releases the key).
With each KeyDown & KeyUp event, it returns e argument of type KeyEventArgs.
KeyEventArgs have following propertry (KeyCode, Handled, Modifiers, Alt, control, KeyData, Keyvalue).

Alt Gets a value indicating whether the ALT key was pressed.
Control Gets a value indicating whether the CTRL key was pressed.
Shift Gets a value indicating whether the SHIFT key was pressed.
Handled Gets or sets a value indicating whether the event was handled. (Set Handled property to
true to cancel the KeyPress event.
KeyCode Gets the keyboard code for a KeyDown or KeyUp event.
KeyData Gets the key data for a KeyDown or KeyUp event.
KeyValue Gets the keyboard value for a KeyDown or KeyUp event.
Modifiers Gets the modifier flags for a KeyDown or KeyUp event. The flags indicate which
combination of CTRL, SHIFT, and ALT keys was pressed.

The KeyChar argument does not report function keys. The event that can capture function keys are
KeyDown event, which is generated when the key is pressed & the KeyUp event, which is generated when
the key is released.
KeyDown event & KeyUp event don’t return the KeyChar but returns the KeyCode (A special
number that distinguishes each key on the keyboard, also known as scancode), through the e.KeyCode
property
The KeyCode is unique for each key, not for each character. Lowercase & Uppercase characters have
different ASCII values but the same KeyCode because they are on the same key. The number 4 and $
symbol have the same KeyCode because the same key on the keyboard generates both character.
The KeyCode for the function key F1 is 112 (or the constant Keys.F12)

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


System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Down Or e.KeyCode = Keys.PageDown Then
SendKeys.Send("{Tab}")
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
ElseIf e.KeyCode = Keys.Up Or e.KeyCode = Keys.PageUp Then
SendKeys.Send("+{Tab}")
End If
End Sub

(18) Enter: -Fired when control received the focus.


(19) Leave: -Fired when control loses the focus.
(20) GotFocus:-Occurs when the control receives focus.

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


System.EventArgs) Handles TextBox1.GotFocus
TextBox1.BackColor = Color.Lavender
TextBox1.Font = New Font("Times New Roman", 8, FontStyle.Bold)
SendKeys.Send("{Home}+{End}")
End Sub

(21) LostFocus: - Occurs when the control loses focus.

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


System.EventArgs) Handles TextBox1.LostFocus
TextBox1.BackColor = Color.White
TextBox1.Font = New Font("Times New Roman", 8, FontStyle.Regular)
End Sub

Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing
custom controls. Enter and Leave events should be used for all controls except the Form class, which uses
the Activated and Deactivate events.
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on) focus events
occur in the following order:
(1) Enter (2) GotFocus (3) Leave (4) Validating (5) Validated (6) LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the
following order
(1) Enter (2) GotFocus (3) LostFocus (4) Leave (5) Validating (6) Validated
If the CausesValidation property is set to false, the Validating and Validated events are suppressed.

(22) Validating: - Occurs when the control is validating. Validating Events .NET gives you two validate
events instead of one: Validating and Validated. Validating is triggered before the control loses the focus.
For example, to make sure that there is something in a textbox, use:
Private Sub TextBox1_Validating (ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text.Trim = String.Empty Then
e.Cancel = True
End If
End Sub
Where the code that sets e.Cancel = True prevents the shift of focus away from the textbox if
there is nothing in the box.
Example: - 2

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
The second example validates an e-mail address that the user enters. If the e-mail address is not in the
standard format (containing "@" and "."), the validation fails, an ErrorProvider icon is displayed, and the
event is canceled.
(22) Validated: - Occurs when the control is finished validating.
. The Validated event, on the other hand, fires after the focus has shifted away from the control, but
before other controls get the focus. Thus, you can use Validated to update the state of the other controls on
the form.
(23)CAUTION: - If you set the CausesValidation property of a control to False, the Validating and
Validated events will not be triggered.

(3) Button Control: -Button control is used to perform some action. Action may be
Save, Delete, Print, Add New, Modify etc. When the button is clicked, it looks as if it is being pushed in and
released. Whenever the user clicks a button, the Click event handler is invoked. You place code in the Click
event handler to perform any action you choose.
The text displayed on the button is contained in the Text property. The Text property can contain an
access key, which allows a user to "click" the control by pressing the ALT key with the access key. The
Button control can also display images using the Image and ImageList properties.

 Property: -

(1)Name
(2)Text: -It is the text that is display on the button control. The Text property can contain an access key,
which allows a user to "click" the control by pressing the ALT key with the access key. If you pale
amperson (&) before any letter, so underscore letter will appear, then user can press alter key with that letter
to fire the Click event.

(3)BackColor (4)ForeColor (5)AuotSize (6)Visible (7)Enable (8)Left (9)Right (10)Top


(11) Bottom (12)Margin (13) Image (14)ImageAlign

(15) TextAlign :- (Same as label control)


(16) Size (17) Location (18) Cursor (19) TabIndex (20) TabStop (21) Font
(22) DialogResult: -Gets or sets a value that is return to the parent form when the button is click.
You can set the way a dialog box is closed at either design time or run time. At design time, you can set the
DialogResult property for all of the Button controls on a dialog box. At run time, you can set the
DialogResult property so you can dynamically handle user responses. Often used when you are creating a
dialog boxes.

 Method of TextBox Control: -

(1) SetBound (2) BringToFront (3) SendToBack


(4) PerformClick: - Generates a Click event for a button. This method raises the click event of the
button control. This method comes handy when the code in the click event has to be executed even when
the user has not clicked the button.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Event of TextBox Control :-


(1) Click (2) DoubleClick (3) MouseDown (4) MouseEnter
(5) MouseHover (6) MouseLeave (7) MouseMove (8) MouseUp
(9) MouseWheel (10) MouseClick (11) MouseDoubleClick
(12) TextChanged (13) KeyPress (14) KeyDown (15) KeyUp (16) Enter
(17) Leave (18) GotFocus (19) LostFocus (20) Validating (21) Validated

(4) Panel Control: (Container Control)


Panel control is used to group other controls. Typically, you use panels to subdivide a form into groups
depending upon the function.
When Panel control is moved, all the controls within it will also be moved.
Panel versus GroupBox
The Panel control is similar to the GroupBox control; however, they have following difference
Panel control can have scroll bars and Panel control dose not display a caption (Label) within it. Panel
control does not have FlatStyle, but it has BorderStyle propertry.
While GroupBox control dose not have scroll bar, but the GroupBox control displays a caption (Label)
within it. GroupBox control does not have BorderStyle, but it has FlatStyle propertry.

 Property : -
(1) BorderStyle: - Gets or sets the border style (border type) for the control. You can use this property to
add a border to the control.
Fixed3D : A three-dimensional border. (2)
FixedSingle : A single-line border. (1)
None : No border. (The default value is none) (0)
(2) BackColor (3) BackgroundImage
(4) AutoScroll: - Panel control support scroll bars. To enable scroll bars in a panel control, set its
AutoScroll property to True.
(5) AutoScrollMargin: -Gets or sets the size of the auto-scroll margin. It is the margin around the
control during the auto scroll. A Size that represents the height and width of the auto-scroll margin in pixels.
Adding Controls to Panels in Code (At runtime):
You can add controls to the panel at run time just as you can add controls to a form. When you add controls
to a form, you use the form’s Contols collection, when you add controls to a panel, you use the panel’s
Controls collection.

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim Panel1 As New Panel()
Dim TextBox1 As New TextBox()

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Panel1.Location = New Point(100, 100)
Panel1.Size = New Size(200, 200)
Panel1.BorderStyle = BorderStyle.Fixed3D

TextBox1.Location = New Point(11, 11)


TextBox1.Size = New Size(170, 100)

Me.Controls.Add(Panel1)
Panel1.Controls.Add(TextBox1)

End Sub
End Class

(5) CheckBox Control: -You can use check box controls in groups to display
multiple choices from which the user can select one or more. (It is used to select one or more oprtions from
the multiple options).
Only one radio button in a group can be selected at a time. With the check box control, however, any
number of check boxes may be selected.

 Property: -
(1) Appearance:-If Appearance value is set to Normal, the CheckBox appears as a typical CheckBox. If
the value is set to Button, the CheckBox appears like a toggle button, which can be toggled to an up or
down state.
(2) FlatStyle: -Gets or sets the flat style appearance of the button control. If the FlatStyle property of the
RadioButton and CheckBox is set to FlatStyle.System, the user’s operating system sets the appearance of
the control.
Flat : The control appears flat.
Popup : A control appears flat until the mouse pointer moves over it, at which point it
appears three- dimensional.
Standard : The control appears three-dimensional. (By Default)
System : The appearance of the control is determined by the user's operating system.
(3) ThreeState:-Gets or sets a value indicating whether the CheckBox will allow three check states rather
than two. By default is False.
If this property is set to True, then the CheckBox has three chceck states namely Checked, Unchecked &
Intermediate. In Intermediate state CheckBox is checked & shaded.
(4) CheckState: -Gets or sets the state of the CheckBox.

CheckState Appearance.Normal
Checked The CheckBox displays a check mark.
Unchecked The CheckBox is empty.
Indeterminate The CheckBox displays a check mark and is shaded.
Intermediate state is sort of middle state between checked
& unchecked.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(5) Checked: -This property is used to check whether the Checkbox is checked or not.. If this property is
true, then the CheckBox is in the checked state. If it is false, then the CheckBox is in unchecked state.
Note
If the ThreeState property is set to true, the Checked property will return true for either a Checked or
IndeterminateCheckState.
(6) Text: -The text displayed within the control is set with the Text property, which can contain access key
shortcuts. An access key enables a user to "click" the control by pressing the ALT key with the access key.

 Event:-
(1) AppearanceChanged: - It occurs when the value of the Appearance property changes.
(2) CheckedChanged: - It occurs when the value of the Checked property changes.
(3) CheckStateChanged: - It occurs when the value of the CheckState property changes.

(6) RadioButton Control: -It is used to select one and only one option from the
available options in one group.
Only one radio button in a group can be selected at a time. With the check box control, however, any
number of check boxes may be selected.

 Property : -
(1) Appearance: -If the Appearance value is set to Normal, then the RadioButton control is drawn with a
circular check box. If the value is set to Button, then the RadioButton is drawn as a control that can be
toggled to an up or down state. Either type can display text, an image, or both.
(2) FlatStyle: -
(3) Checked: - This property is used to check whether the RadioButton is selected or not. If this property
is true, then RadioButton is selected.
(4) Text: -The text displayed within the control is set with the Text property, which can contain access key
shortcuts. An access key enables a user to "click" the control by pressing the ALT key with the access key.

 Method: -
(1) Performclick: - Generates a Click event for the control, simulating a click by a user.

 Event :-
(1) AppearanceChanged: -It occurs when the value of the Appearance property changes.
(2) CheckedChanged: - It occurs when the value of the Checked property changes.

. (7) GroupBox Control: (Container Control)


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
GroupBox control is used to group other controls. Typically, you use GropuBox to subdivide a form into
groups depending upon the function.
When GroupBox control is moved, all the controls within it will also be moved.

Panel versus GroupBox


The Panel control is similar to the GroupBox control; however, they have following difference
Panel control can have scroll bars and Panel control dose not display a caption (Label) within it. Panel
control does not have FlatStyle, but it has BorderStyle propertry.
While GroupBox control dose not have scroll bar, but the GroupBox control displays a caption (Label)
within it. GroupBox control does not have BorderStyle, but it has FlatStyle propertry.

 Property : -
(1) FlatStyle: - Gets or sets the flat style appearance of the group box control.
Flat : The control appears flat.
Popup : A control appears flat until the mouse pointer moves over it, at which point it appears
three-dimensional.
Standard : The control appears three-dimensional.
System : The appearance of the control is determined by the user's operating system.

(2) BackColor : (3) BackgroundImage :

 Adding Controls to Panels in Code (At runtime)


You can add controls to the GroupBox at run time just as you can add controls to a form. When you
add controls to a form, you use the form’s Contols collection, when you add controls to a GroupBox, you
use the GroupBox’s Controls collection.
The following code example instantiates and creates a GroupBox and two RadioButton controls.
The option buttons (also known as radio buttons) are added to the group box and the group box is added to
the Form.

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


System.EventArgs) Handles MyBase.Load
' Create and initialize a GroupBox and two RadioButton controls.
Dim GroupBox1 As New GroupBox()
Dim RadioButton1 As New RadioButton()
Dim RadioButton2 As New RadioButton()

' Set the FlatStyle of the GroupBox.


GroupBox1.FlatStyle = FlatStyle.System

GroupBox1.Location = New Point(100, 100)


GroupBox1.Size = New Size(300, 300)

RadioButton1.Location = New Point(16, 16)


RadioButton1.Size = New Size(120, 20)
RadioButton2.Location = New Point(16, 40)
RadioButton2.Size = New Size(120, 20)

' Add the RadioButtons to the GroupBox.


GroupBox1.Controls.Add(RadioButton1)
GroupBox1.Controls.Add(RadioButton2)

' Add the GroupBox to the Form.


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Me.Controls.Add(GroupBox1)
End Sub

(7) ListBox Control: -


ListBox control displays a list of items from which the user can select one or more items. If the total
number of items exceeds the number that can be displayed, a scroll bar is automatically added to the
ListBox control.
Advantage of ListBox is (i) user dis not have to remember all possible options. (ii) It also prevent
wrong entry because, user did not have to type.
You can add or remove items to a ListBox either at design time or at run time.
To add or remove items at design time you can use Items property, whis is a very handy array of
items in the ListBox.
To add items at run time, you can use Items.Add OR Items.Insert OR Items.AddRange method.
To remove items at run time, you can use Items.Remove OR Items.RemoveAt method.
To remove all the item at run time, you can use Items.Clear method.

When the MultiColumn property is set to true, the list box displays items in multiple columns and a
horizontal scroll bar appears. When the MultiColumn property is set to false, the list box displays items in a
single column and a vertical scroll bar appears. When ScrollAlwaysVisible is set to true, the scroll bar
appears regardless of the number of items. The SelectionMode property determines how many list items can
be selected at a time.
 You can use Clear methos of the Items collection to clear a ListBox.
For example ListBox1.Items.Clear ()
 At run time you can use add method, to isert an item into the ListBox.
For Example ListBox1.Items.Add (“Bollpen”)
OR
Or, you can use Insert method, to inserts an item into the list box at the specified index.
ListBox1.Items.Insert(Index As Integer, Item As Object)

For Example ListBox1.Items.Insert (3, “Eraser”)


OR
Or, you can also use AddRange method, to add a set of items to the list box in a single operation,
For Example
Dim DataArray (20) As String
…….
………
ListBox1.Items.AddRange (DataArraty)

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 At run time you can use remove method, to remove a specific item from the the ListBox.
For example to remove a currently selected item
ListBox1.Items.Remove (ListBox1.SelectedItem)
You can also remove an item by passing corresponding object to remove.
ListBox1.Items.Remove (“Bollpen”)
OR
Or, you can use RemoveAt method to delete items from a ListBox.
For example,
To remove the item at index 5. ListBox1.Items.RemoveAt (5)
Or, you can also remove the currently selected item with RemoveAt
ListBox1.Items.RemoveAt (ListBox1.SelectedIndex)

 Property: -
(1) MultiColumn: -Gets or sets a value indicating whether the ListBox supports multiple columns.
When the MultiColumn property is set to true, the list box displays items in multiple columns and a
horizontal scroll bar appears if total number of items exceeds. When the MultiColumn property is set to
false, the list box displays items in a single column and a vertical scroll bar appears if total number of items
exceeds.

(2) ScrollAlwaysVisible: - When ScrollAlwaysVisible is set to true, the scroll bar appears regardless
of the number of items. (A scroll bar always appears).
(3) Sorted: -Gets or sets a value indicating whether the items in the ListBox are sorted alphabetically. If
Sorted property is set to True, then the items are automatically sort strings alphabetically in a ListBox.
(4) Text: - Gets or searches for the text of the currently selected item in the ListBox. This property
represents the text of the item that is currently selected.
(5) SelectionMode: - Gets or sets the method in which items are selected in the ListBox. How many
items can be selected at a time and how the user can make multiple-selections..You can set this property to
None, One, Multisimple, or MultiExtended.

MultiExtended Multiple items can be selected, and the user can use the SHIFT, CTRL, and
arrow keys to make 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.
MultiSimple Multiple items can be selected.
When the property is set to SelectionMode.MultiSimple, a mouse click or
pressing the SPACEBAR selects or deselects an item in the list.
None No items can be selected.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
One Only one item can be selected. (By Default)

(6) Items: - This property is used to view and change the items in the ListBox. Display this editor from the
properties window by clicking the ellipsis (…) button next to the Items property of the control.
The items in the list boxes are stored in the Items collection.
You can add items to a ListBox either at design time or at run time. The first item will have index 0,
the next item will have index 1, and so on in the ListBox.
At design time you can use Items property, whis is a very handy array of items in the ListBox.
At Run time use the Items.Add method.
Items.Count property holds the total no of items in the list.
(7) SelectedItem:-Gets or sets the currently selected item in the ListBox. This property represents the
item that is currently selected.
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.
(8) SelectedItems: - Gets a collection containing the currently selected items in the ListBox. This
property representrs a collection of all the items that are currently selected.
(9) SelectedIndex: -Gets or sets the index of the currently selected item in the ListBox. This property is
used to find out the index number of the currently selected item.
If no item is selected in the listbox, then SelectedIndex prpperty will return -1.
(10) SelectedIndices: -Gets a collection containing the indexes of all currently selected items in the
ListBox . This property representrs a collection of all the indexes that are currently selected.

 Methods : -

(1) ClaerSelected: Unselects all items in the ListBox.


Calling this method is equivalent to setting the SelectedIndex property to negative one (-1). You can use this
method to quickly unselect all items in the list.
(2) GetSelected: Returns a value indicating whether the specified item is selected. This method returns a
True if the specified item is selected & returns a False if the specified item is not selected.
ListBox1.GetSelected (Index As Integer) As Boolean
(3) SetSelected: This method is used to select or unselect the specified item. A Boolean True value can
be passed to this method to select the item.
ListBox1.SetSelected (Index As Integer, Valuse As Boolean)
For example
‘Select three items from the ListBox.
ListBox1.SetSelected (1, True)
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
ListBox1.SetSelected (3, True)
ListBox1.SetSelected (5, True)

(4) BeginUpdate : (5) EndUpdate : -These enable you to add a large number of items to the ListBox
without the ListBox being redrawn each time an item is added to the list..

The preferred way to add multiple items to the ListBox is to use the AddRange method of the
ListBox.ObjectCollection class (through the Items property of the ListBox). This enables you to add an
array of items to the list in a single operation. However, if you want to add items one at a time using the Add
method of the ListBox.ObjectCollection class, you can use the BeginUpdate method to prevent the
control from repainting the ListBox each time an item is added to the list. Once you have completed the
task of adding items to the list, call the EndUpdate method to enable the ListBox to repaint. This way of
adding items can prevent flickered drawing of the ListBox when a large number of items are being added to
thelist.

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


System.EventArgs) Handles Button1.Click
ListBox1.BeginUpdate()
Dim I As Integer
For I = 1 To 20
ListBox1.Items.Add("Item " & I.ToString())
Next I
ListBox1.EndUpdate()
End Sub

(6) FindString: Finds the first item in the ListBox that starts with the specified string.
Syntax: 1
ListBox.FindString (S as String)
Finds the first item in the ListBox that starts with the specified string.
Syntax: 2
ListBox.FindString (S as String, StartIndex as integer)
Finds the first item in the ListBox that starts with the specified string. The search starts at a specific
starting index.
(7) FindStringExact: Finds the first item in the ListBox that exactly matches the specified string.
ListBox. FindStringExact (S as String)
OR
ListBox. FindStringExact (S as String, StartIndex as integer)

 Events :-

(1) SelectedIndexChanged: Occurs when the value of the SelectedIndex property has changed.

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


System.EventArgs) Handles
ListBox1.SelectedIndexChanged
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
End Sub

(8) CheckedListBox Control: -CheckedListBox control is derived from


standard LisxtBox, except that them it also supports a checkbox for each item. It does almost everything that
a list box does and also can display a check mark next to items in the list. Differences between the two
controls are that multiselection is not supported in checked list box control; it means only have one item or
none item can be selected.

As with standard listbox, you can access the items in a check list box using the Items property. To
check an item, the user has to double click a checkbox by default, unless you set the CheckOnClick
propertry to True, in which case it only takes one click.

 Property : -
(1) CheckedItems: This propert refers to the collection of all the checked items in the CheckedListBox
control.

(2) CheckedIndices: This propert refers to the collection of indexes of all the checked items in the
CheckedListBox control.

(3) GetItemChecked: Returns a value indicating whether the specified item is checked. This method
returns a True if the specified item is checked & returns a False if the specified item is not checked.
CheckedListBox1.GetItemChecked (Index As Integer) As Boolean
(4) SetItemChecked: This method is used to check or uncheck the specified item. A boolean True value
can be passed to this method to check the item.
CheckedListBox1.SetItemChecked (Index As Integer, Valuse As Boolean)
For example
‘To check the three items from the ListBox’
CheckedListBox1.SetItemChecked (1, True)
CheckedListBox1.SetItemChecked (3, True)
CheckedListBox1.SetItemChecked (5, True)

Note: To use three-state checkboxes, you use the GetItemCheckState & SetItemChecked methods
instead of GetItemChecked & SetItemChecked methods.

 Events :-

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(1) SelectedIndexChanged: Occurs when the value of the SelectedIndex property has changed.

Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles Checked
ListBox1.SelectedIndexChanged
End Sub

(2) ItemCheck: This event is triggered when the checkedstate of the item is changed.

(9) ComboBox Control: -


ComboBox control is used to display data in a drop-down combo box. The ComboBox control is
made up of 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.
You can add or remove items to a ComboBox either at design time or at run time.
To add or remove items at design time you can use Items property, whis is a very handy array of
items in the ComboBox.
To add items at run time, you can use Items.Add OR Items.Insert OR Items.AddRange method.
To remove items at run time, you can use Items.Remove OR Items.RemoveAt method.
To remove all the item at run time, you can use Items.Clear method.

 Property : -
(1) DropDownStyle: Gets or sets a value specifying the style of the combo box. This property represents
the style of the combo box control. The different style are (a) Simple (b) DropDwon & (c) DropDownList.
(a) Simple: It is the ComboBox without drop down arrow. It contain text box & list box that does
not drop down. User can select from the list or type in to the text box.

(b) DropDwon: It is the by default style. User can eiter type the text directly or select the item from
the drop down list.

(c) DropDownList: Display list box when user click on the drop down arrow. User can only select
an item from the list; user can not enter text in the text box.

(2) Focused: Gets a value indicating whether the control has input focus. It returns True if the control has
focus.
(3)MaxDropDownItems: This property represents the maximum numbers of items that will be display
in the drop down portion when the drop down arrow on the ComboBoc control is click.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(4) Text: Gets or searches for the text of the currently selected item in the ListBox. This property
represents the text of the item that is currently selected.
(5) Items: This property is used to view and change the items in the ListBox. Display this editor from the
properties window by clicking the ellipsis (…) button next to the Items property of the control.
The items in the list boxes are stored in the Items collection.
You can add items to a ListBox either at design time or at run time. The first item will have index 0,
the next item will have index 1, and so on in the ListBox.
At design time you can use Items property, whis is a very handy array of items in the ListBox..
At Run time use the Items.Add method.
Items.Count property holds the total no of items in the list.
(6) SelectedItem: Gets or sets the currently selected item in the ComboBox. This property represents the
item that is currently selected.
(7) SelectedIndex: Gets or sets the index of the currently selected item in the ListBox. This property is
used to find out the index number of the currently selected item.
If no item is selected in the listbox, then SelectedIndex prpperty will return -1.

 Methods : -
(1) BeginUpdate: (2) EndUpdate (3) FindString (4) FindStringExact

 Events: -
(1) SelectedIndexChanged: Occurs when the value of the SelectedIndex property has changed.

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


As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
End Sub

(2) DropDownStyleChanged: It occurs when the value of the DropDownStyle property has changed.

(10) PictureBox Control: -The Windows Forms PictureBox control is used to


display graphics in bitmap, GIF, JPEG, metafile, or icon format. To display an image in picture box, you can
set the Image property. Image can be set at design time or at run time.

 Property :-
(1)Image: Gets or sets the image that the PictureBox displays. This property is used to specify the image
that the picture box dispays. . Image can be set at design time or at run time. At design time you can add an
image to the PictureBox using Image property.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
At run time you have to set the Image property to an Image object, which you can crerte using the
Image class’s FromFile method. This method can load images from bitmap (.bmp), icon (.ico) or metafile
(.wmf), JPEG (.jpg), GIF (.gif) files, and other types of files.
PictureBox1.Image = Image.FromFile("c:\My Document\OM.bmp")

(2)SizeMode : Indicates how the image is displayed. This property is used to specify the way the image is
displayed. The different size modes that can be specified are Normal, StretchImage, AutoSize, CenterImage
or Zoom. The default is Normal.
 Normal: The upper-left corner of the image is placed at upper-left in the PictureBox. The image is
clipped if it is larger than the PictureBox it is contained in. The default is Normal.
 StretchImage: The image within the PictureBox is stretched or shrunk to fit the size of the
PictureBox. The image will automatically resize to the size of the PictureBox control.
 AutoSize: The PictureBox control is sized equal to the size of the image that it contains. The
PictureBox control will automatically resize to the size of the image.
 CenterImage: The image is displayed in the center if the PictureBox is larger than the image. If
the image is larger than the PictureBox, the picture is placed in the center of the PictureBox and the
outside edges are clipped.
 Zoom: The size of the image is increased or decreased maintaining the size ratio.
 Event :-

(1) SizeModeChanged: This event is occurs when SizeMode property is changed. The SizeMode
property can be changed programmatically.

(11) Scroll Bars Control:-ScrollBar controls are used to provide easy navigation
through a long list of items or a large amount of information by scrolling either horizontally or vertically
within an application or control. Scroll bar allows user to select a value by positioning the scroll box
(thumb) to desire position (instead of typing a value). Scroll bars are a common element of the Windows
interface. Many developers choose to incorporate the ScrollBar control when authoring their own user
controls.
The HScrollBar (horizontal) and VScrollBar (vertical) controls operate independently from other
controls and have their own set of events, properties, and methods.
The ScrollBar controls use the Scroll event to monitor the movement of the scroll box (sometimes
referred to as the thumb) along the scroll bar. Using the Scroll event provides access to the scroll bar value
as it is being dragged.

SmallChange SmallChange
Scroll Box (Thumb)

LargeChange
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Property :-
(1) Value: Gets or sets a numeric value that represents the current position of the scroll box (thumb) on the
scroll bar control. The Value property (which, by default, is 0) is an integer value corresponding to the
position of the scroll box in the scroll bar.

(2) Minimum: Gets or sets the lower limit of the scrollable range. (By default, is 0).
(3) Maximum: Gets or sets the upper limit of the scrollable range. (By default, is 100).
(4) SmallChange: Gets or sets the value to be added to or subtracted from the Value property when user
clicks an arrow button. (By default is 1).

When the user presses one of the arrow keys or clicks one of the scroll bar arrow buttons, the Value
property changes according to the value set in the SmallChange property.

(5) LargeChange: Gets or sets a value to be added to or subtracted from the Value property when the
user clicks in the blank area of the scroll box. (Outside the scroll box). The default value is 10

When the user presses the PAGE UP or PAGE DOWN key or clicks in the scroll bar track on either
side of the scroll box, the Value property changes according to the value set in the LargeChange property.

 Event: -
(1) Scroll: This event is triggered when the scroll box has been moved (either by the mouse or keyboard).
Private Sub HScrollBar1_Scroll (ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ScrollEventArgs) Handles
HScrollBar1.Scroll
End Sub
(2)ValueChanged: It occurs when the Value property has changed, either by a Scroll event or
programmatically.

(12) Track Bars Control: -TrackBar control is very much like scroll bars but
differ in appearance. TrackBar control (also sometimes called a "slider" control) is used for navigating
through a large amount of information or for visually adjusting a numeric setting. The TrackBar control has
two parts: the thumb, also known as a slider, and the tick marks. The thumb is the part that can be adjusted.
Its position corresponds to the Value property. The tick marks are visual indicators that are spaced at regular
intervals. The trackbar moves in increments that you specify and can be aligned horizontally or vertically.
For example, you might use the track bar to control the cursor blink rate or mouse speed for a system.

l| | | | | | | | | |

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Property: -

(1) Orientation: Gets or sets a value indicating the horizontal or vertical orientation of the track bar. Track
bar can be display horizontally or vertically.

(2) Value: Gets or sets a numeric value that represents the current position of the slider in the track bar.
(By default, is 0)

(3) Minimum: Gets or sets the lower limit of the Track scrollable range. (By default, is 0).

(4) Maximum: Gets or sets the upper limit of the Track scrollable range. (By default, is 10).

(5) SmallChange: Gets or sets the value to be added to or subtracted from the Value property when user
clicks an arrow button. (By default is 1).

The value of the SmallChange property is the number of positions the thumb (slider) moves in
response to having the LEFT or RIGHT ARROW key pressed.

(6) LargeChange: Gets or sets a value to be added to or subtracted from the Value property when the
user clicks clicks on the track bar on either side of the thumb.

The value of the LargeChange property is the number of positions the thumb moves in response to
having the PAGE UP or PAGE DOWN key pressed, or in response to mouse clicks on the track bar on
either side of the thumb.

(7) TickStyle: Gets or sets a value indicating how to display the tick marks on the track bar.
 Both: Tick marks are located on both sides of the control.
 BottomRight: Tick marks are located on the bottom of a horizontal control or on the right side of a
vertical control. The default is TickStyle.BottomRight
 None: No tick marks appear in the control.
 TopLeft: Tick marks are located on the top of a horizontal control or on the left of a vertical
control.

(8)Tickfrequency: Gets or sets a value that specifies the distance between ticks. The default is 1.
For example, if you have a control with a range of 100, passing in a value of 5 here causes the control to
draw 20 ticks. In this case, each tick represents five units in the range of values.

 Event: -
(1) Scroll: This event is triggered when the slider moves (either by the mouse or keyboard).
(2)ValueChanged: It occurs when the Value property of a track bar changes (either by moving the slider
or through code).

(13) Splitters Control:-


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Splitter controls are used to resize docked controls at run time. You can use splitters to let the user
resize controls. The Splitter control is often used on forms with controls that have varying lengths of data to
present, like Windows Explorer, whose data panes contain information of varying widths at different times.
Here is how it works: you add a control to a form and then dock it. Next, you add a aplitter control
and dock it to the same size of the same container. When you run a program splitter is invisible until the
mouse passes over it. As soon as the mouse cursor passes over the splitter, it changes, indicating that the
control can be resized.
Therefore, to enable the user to resize a docked control at run time, dock the control to be resized to
an edge of a container.
You can enable or disable the splitter with the Enabled property, set the cursor that appears with the
splitter with the Cursor property (for vertical splitter the default cursor is VSplit, for horizontal splitter the
default cursor is HSplit.
Important: Although SplitContainer control replaces and adds functionality to the Splitter control of
previous versions, Splitter is retained for both backward compatibility and future use if you choose.

(14) SplitContainer Control:-


Important: In the Toolbox, SplitContainer control replaces the Splitter control that was there in the
previous version of Visual Studio. The SplitContainer control is much preferred over the Splitter control.
The Splitter class is still included in the .NET Framework for compatibility with existing applications, but
we strongly encourage you to use the SplitContainer control for new projects.

SplitContainer control contains two panels that are separated by a movable bar. When the mouse
pointer is over the bar, the pointer changes shape to show that the bar is movable. You can drop other
controls on these panels & arrange them as you like.

Using SplitContainer Control, creating splitter based user interface becomes much easeier task..
The SplitContainer control is often used on forms with controls that have varying lengths of data to
present, like Windows Explorer, whose data panes contain information of varying widths at different times.

Panel1

Dr.Krunal Bhavsar
Panel1
[Ph.D Panel2
in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

 Property :-
(1) FixedPanel: Gets or sets which SplitContainer panel remains the same size when the container is
resized.
Use this property to specify which SplitContainer panel stays the same size when a user resizes the
container. That is either Panel1 or Panel2 or None (By Default).
(2) IsSplitterFixed: Determines if the splitter can be moved with the keyboard or mouse. If it is set to
True then, the splitter is fixed. If it is set to False splitter is movable with the keyboard or mouse. The default
is false.
(3) Orientation: Orientation property is used to change the orientation of the SplitContainer panels
from vertical to horizontal or from horizontal to vertical.

 Event: -
(1) SplitterMoving: Occurs when the splitter control is moving.
(2) SplitterMoved: Occurs when the splitter control has moved. The SplitterMoved event is raised
when you stop moving the splitter control.

(15) DateTimePicker Control: (Pickers)


It is used to select a date and a time and to display the date and time with a specified format.
The DateTimePicker control displays a graphical calendar from which users can select (set) a date
required by them. If you click the arrow in the date-time picker, it displays a month calendar, just as a
combo box would display a drop-down list. Using the DateTimePicker eliminates much of the need for
validating date/time values.

If you wish the DateTimePicker to appear as a control for picking or editing times instead of dates,
set the ShowUpDown property to true and the Format property to Time.

You can limit the date & time that can be selecected in a DateTimePicker control by setting the
MinDate & MaxDate property. You can even change the look of the control within the calendar part of the
control by setting the CalendarForeColor, CalendarFont, CalendarTitleBackColor, CalendarTitleForeColor,
CalendarTrailingForeColor & CalendarMonthBackground properties.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Property :-
(1) MaxDate: Gets or sets the maximum date and time that can be selected in the control.
(2) MinDate: Gets or sets the minimum date and time that can be selected in the control.
(3) Format: Gets or sets the format of the date and time displayed in the control. The date/time format is
based on the user's regional settings in their operating system. The default is long.
To display only time in a DateTimePicker, set the Format to Time, and the ShowUpDown property
to false.
Custom : The DateTimePicker control displays the date/time value in a custom format. If the
format poperty is set to custom (DateTimePickerFormat.Custom), you can create your
own format style by setting the CustomFormat property.
Long : The DateTimePicker control displays the date/time value in the long date format set by
the user's operating system.
Short : The DateTimePicker control displays the date/time value in the short date format set by
the user's operating system.
Time : The DateTimePicker control displays the date/time value in the time format set by the
user's operating system.

(4) CustomForamt: Gets or sets the custom date/time format string.


d - The one-or-two digit day.
dd - The two digit day. Single digit day values are preceded by a zero,
ddd – Three character day-of-week abbreviation.
dddd - The full day-of-week name.
h – The one or two digit hour in 12 hour format.
hh - The two digit hour in 12 hour format. Single digit day values are preceded by a zero,
H – The one or two digit hour in 24 hour format.
HH – The two digit hour in 24 hour format. Single digit day values are preceded by a zero,
MMM – The three character month abbreviation.
Etc….

(5) ShowDropDown: Gets or sets a value indicating whether a spin button control (also known as an up-
down control) is used to adjust the date/time value.
To display only time in a DateTimePicker, set the Format property to Time, and the ShowUpDown
property to false.

 Event: -
(1) DropDown: Occurs when the drop-down calendar is appears (shown).
(2) CloseUp: Occurs when the drop-down calendar is disappears.
(3) ValueChanged: It Occurs when the Value property changes.
(4) FormatChanged: It occurs when the Format property value has changed.

(16) MonthCalendar Control: (Pickers)


Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
MonthCalendar control enables the user to select a date using a visual monthly calendar display.
MonthCalendar control presents a graphical interface for users to view and set date information. The control
displays a calendar. The selected range of dates is highlighted.

You can limit the date and times that can be selected by setting the MinDate and MaxDate
properties.
You can change the look of the calendar portion of the control by setting the ForeColor, Font,
TitleBackColor, TitleForeColor, TrailingForeColor, and BackColor properties.

The key property of the MonthCalendar control is SelectionRange, the range of dates selected in
the control.

 Property :-
(1) MaxDate: Gets or sets the maximum allowable date that can be selected in the control.
(2) MinDate: Gets or sets the minimum allowable date that can be selected in the control.
(3) BoldedDates: Gets or sets an array of DateTime specifying which days should be bold.
(4) FirstDayOfweek: Gets or sets the first day of the week as displayed in the month calendar.
(5) ShowToday: Gets or sets a value indicating whether the today’s date is shown at the bottom of the
control. (By default is True).
(6) ShowTodayCircle: Gets or sets a value indicating whether today's date should appear inside a
circled. (By default is True).
(7) ShowWeekNumbers: Gets or sets a value indicating whether the month calendar control displays
week numbers (1-52) to the left of each row of days. The default is False.
(8) TodayDate: Gets or sets the today’s date. This value is used by MonthCalendar control as today's
date.

 Event: -
(1) DateChanged : It occurs when the date in the MonthCalendar control changes.
(2) DateSelected : Occurs when the user makes an explicit date selection using the mouse.
This event is similar to the DateChanged event, but it occurs at the end of a date selection made
using the mouse. The DateChanged event occurs during any date selection, whether by mouse, keyboard, or
code.

(17) NotifyIcon Control:


Notify icons let you display an icon in the status notification area of the Windows taskbar (at
extreme right in the taskbar) called the Windows system tray.

Icons in the notification area are shortcuts to processes that are running in the background of a
computer, such as a virus protection program or a volume control.

Each NotifyIcon component displays a single icon in the status area. If you have three background
processes and wish to display an icon for each, you must add three NotifyIcon components to the form. The
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
key properties of the NotifyIcon component are Icon and Visible. The Icon property sets the icon that
appears in the status area. In order for the icon to appear, the Visible property must be set to true.
You can associate balloon tips, shortcut menus, and ToolTips with a NotifyIcon to assist the user.

 Property :-
(1) Icon: Gets or sets the current icon. The Icon displayed by the NotifyIcon component. The default value
is a null reference (Nothing in Visual Basic).

(2) ContextMenuStrip: Gets or sets the shortcut menu (context menu) for the NotifyIcon (traty icon)

(3) Text: Gets or sets the ToolTip text which is to be displayed when the mouse pointer rests on a
notification area icon. (System tray icon).

(4) Visible: Gets or sets a value indicating whether the icon is visible in the notification area of the
taskbar.

(5) BalloonTipIcon: Gets or sets the icon to display on the balloon tip associated with the NotifyIcon.

(6) BalloonTipText: Gets or sets the text to display on the balloon tip associated with the NotifyIcon.

(7) BalloonTipTitle: Gets or sets the title of the ballon tip display on the NotifyIcon.

 Event: -
(1) Click: It occurs when the user clicks the NotifyIcon (system tray icon) with the mouse.

(2) DoubleClick: It occurs when the user double clicks the NotifyIcon (system tray icon) with the mouse.

(3) MouseDown: Occurs when the user presses the mouse button on the icon in the system tray.
(4) MouseUp: & (5) MouseMove:

(18) Tool Tips Control:


Tool Tip control is used to display a small rectangular pop-up window that displays (appears) with
explanatory text when the user rests the mouse pointer on the control. Tool tips are used to give quick help
when the mouse pointer rests on the control
With the ToolTip class, you can provide hints to a user when the user places the pointer on a control.
The ToolTip class is typically used to alert users to the intended use of a control. For example, you can
specify ToolTip text for button control that to display a function of a button.

Tool tips are components, not controls. So when you add them to a form, they will appear in a
component tray.
A single ToolTip component typically is used to create ToolTips for multiple controls on a single
form. After you create a ToolTip, use a separate call (SetToolTip method) for individual controls.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Property :-
(1) Active: Gets or sets a value indicating whether the ToolTip is currently active. The default is true.
With the Active property, you can enable or disable the display of ToolTip text for all controls that have text
specified by this particular ToolTip component.
(2) AutomaticDelay: Gets or sets the time (in milliseconds) before the tool tip appears. The default is
500. It specifies the time that should elapsed before the toop tip is displayed, when the mouse pointer is
moved over trhe control.
(3) InitialDelay: It is used to specify how long the mouse pointer should remain on the control before the
tooltip be displayed. Gets or sets the time that passes before the ToolTip appears.
(4) ShowAlways: It is used to specify whether the tool tip should be sidplayed even if the associated
control is not active. If this value is set to True, the tool tips will be displayed irrespective of whether the
control is active or not.

 Event: -
(1) SetToolTip: This method is used to set the ToolTip text with the specified control.
ToolTip1 (Control, Caption)
Example: ToolTip1 (Me.button1, "My button1")

(2) GetToolTip: This method is used to retrieve the ToolTip text for a specified control.
ToolTip1 (Control) As String
Example: ToolTip1 (Me.button1)  my button1

(3) RemoveAll: This method is used to remove all the Tool Tips text corresponding to a specific ToolTip
component.

(19) Timer Control:-


Timer is a component that raises an event at regular intervals. (at regular user-defined intervals).
Timer is a component not control. So when you add them to a form, they will appear in a component tray at
design time and it will not appear in a form at run time.

The code written in a tick event is executed at predefined regular interval. The interval property is
used to set the time gape between the code executions. (Set in millisecond).

The key methods of the Timer component are Start and Stop, which turn the timer on and off. When
the timer is switched off, it resets; there is no way to pause a Timer component. You can also use enabled
property of timer component to Start (on) and Stop (off) the timer.

 Property :-
(1) Enabled: Gets or sets whether the timer is running. If it is set to true, then the timer is currently
enabled (on). If it is set to false, then the timer is currently disable (off). The default is false.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(2) Interval: Gets or sets the time, in milliseconds, that represents the time period between each timer
ticks. The interval property is used to set the time gape between the code executions.
It is in milliseconds. To get the number of seconds in the interval, divide this number by 1000. The default
value is 100 milliseconds.

 Methods : -
(1) Start: It starts the timer. You can also start the timer by setting the Enabled property to true.
(2) Stop: It stops the timer. You can also stop the timer by setting the Enabled property to false.

 Event: -
(1) Tick: This event is triggered (executed) when the specified timer interval has elapsed and the timer is
enabled.

(20) RichTextBox Control:-


RichTextBox control is used for displaying, entering, and manipulating text with formatting. The
RichTextBox control does everything the TextBox control does, but it can also display fonts, colors, and
links; load text and embedded images from a file; and find specified characters. Text can be assigned
directly to the control, or can be loaded from a rich text format (RTF) or plain text file. The text within the
control can be assigned character and paragraph formatting.

The RichTextBox control is typically used to provide text manipulation and display features similar
to word processing applications such as Microsoft Word.

The control also provides more advanced formatting features than the standard TextBox control.
Text can be assigned directly to the control, or can be loaded from a Rich Text Format (RTF) or plain text
file. The text within the control can be assigned character and paragraph formatting.

You can also use a RichTextBox control for Web-style links by setting the DetectUrls property to
true and writing code to handle the LinkClicked event. You can prevent the user from manipulating some or
all of the text in the control by setting the SelectionProtected property to true. You can use the Find method
to find strings of text or specific characters.

 Property :-
(1)Name,(2)Text,(3)BackColor,(4)ForeColor,(5)Visible,(6)Enabled,(7)Left,(8)Right,(9)Top,(10)Bottom
(11)Margin,(12)BorderStyle,(13) Size,(14) Location,(15) Cursor,(16) HideSelection :
(17) MultiLine: Gets or sets a value indicating whether this is a multiline RichTextBox control. (By
default is true).
(18) Lines, (24) ReadOnly, (25) Locked, (26) WordWrap
(27) SelectedText: (Only available at run time, Dynamic property): Gets or sets a value indicating the
currently selected text in the control. If no text is currently selected in the text box, this property returns a
zero-lengthstring.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(28) SelectionLength: (Only available at run time, Dynamic property) : Gets or sets the number of
characters selected in the text box.

(29) SelectionStart: (Only available at run time, Dynamic property) : Gets or sets the starting point
of text selected in the text box. If no text is selected in the control, this property indicates the insertion point
for new text.

(30) TextLength: Gets the length of text in the control. It is used to get The number of characters
contained in the text of the control.
For ex.1 MsgBox (RichTextBox1.TextLength)

Example 2 Dim Strlen As Integer


Strlen = RichTextBox1.TextLength

(31) DetectUrls: Gets or sets a value indicating whether or not the RichTextBox will automatically
format a Uniform Resource Locator (URL) when it is typed into the control.
When this property is set to true the RichTextBox will automatically format the URL when it is
typed into the control.When this property is set to false the RichTextBox considers the URL as a normal
text.

(32) SelectionIndent: Indents first line ofparagraph.

(33) SelectionRightIndent: Sets the right indentation of the paragraph.

(34) SelectionHangingIndent: Indents all other lines of paragraph with respect to SelectionIndent.

(35) SelectionBullet: Gets or sets a value indicating whether the bullet style is applied to the current
selection or insertion point.

(36) SelectionAlignment: Gets or sets the alignment to apply to the current selection or insertion point.
It can be Left or Center or Right.
For example: RichTextBox1.SelectionAlignment = HorizontalAlignment.Center
(37) SelectionColor: Gets or sets the text color of the current text selection or insertion point.
(38) SelectionFont: Gets or sets the font of the current text selection or insertion point.
(39) SelectionTabs: Gets or sets the absolute tab stop positions in a RichTextBox control.
(40) ZoomFactor: Gets or sets the current zoom level of the RichTextBox. The value of this property
can be between 1/64 and 64.0. A value of 1.0 indicates that no zoom is applied to the control.

 Methods : -
(1) SetBound (2) BringToFront (3) SendToBack (4) AppendText (6) Copy (7) Cut (8) Paste
(9) SelectAll (10) Undo (11) Redo

(12) LoadFile: Loads the contents of the specified file into the RichTextBox control. The LoadFile
method enables you to load an existing RTF or ASCII text file into the RichTextBox control.
For example:
OpenFileDialog1.ShowDialog ()
RichTextBox1.LoadFile (OpenFileDialog1.FileName)
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(13) SaveFile: Saves the contents of the RichTextBox to a file. The SaveFile enables you to save a file to
RTF or ASCII text.

For example:
SaveFileDialog1.ShowDialog()
RichTextBox1.SaveFile(SaveFileDialog1.FileName)

(14) Find: It searches for specified text within the contents of the RichTextBox control.
For example: Dim posi As Integer = RichTextBox1.Find(s)

 Event: -
(1) LinkClicked: Triggered when the user clicks on a link within the text of the RichTextBox control.
(2) SelectionChanged: Triggered when the selection of text within the RichTextBox control has
changed.

(21) MaskedTextBox Control:


The MaskedTextBox class is an enhanced TextBox control that supports a declarative syntax for
accepting or rejecting user input.
OR
The MaskedTextBox is an improvement upon text box controls in that they let you specify a format
for input and avoid wrongly formatted or unexpected inputs.

Using the Mask property, you can specify the following input without writing any custom validation
logic in your application:

 Required input characters.


 Optional input characters.
 The type of input expected at a given position in the mask; for example, a digit, or an alphabetic or
alphanumeric character.
 Mask literals, or characters that should appear directly in the MaskedTextBox; for example, the
hyphens (-) in a phone number, or the currency symbol in a price.
 Special processing for input characters; for example, to convert alphabetic characters to uppercase.

When a MaskedTextBox control is displayed at run time, it represents the mask as a series of prompt
characters and optional literal characters. As the user types input into the masked text box, valid input
characters replace their respective prompt characters in a sequential fashion. If the user types an invalid
input character, no replacement occurs, but instead a beep is issued if the BeepOnError property is set to
true, and the MaskInputRejected event is raised. You can provide your own custom error logic by handing
this event.

 Property :-
(1) Mask: Gets or sets the input mask to use at run time. A String representing the current mask. The
default value is the empty string which allows any input.
Mask must be a string composed of one or more of the masking elements, as shown in the following table.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

Masking
Description
element
0 Digit, required. This element will accept any single digit between 0 and 9.
9 Digit or space, optional.
Digit or space, optional. If this position is blank in the mask, it will be rendered as a
#
space in the Text property. Plus (+) and minus (-) signs are allowed.
Letter, required. Restricts input to the ASCII letters a-z and A-Z. This mask element is
L
equivalent to [a-zA-Z] in regular expressions.
Letter, optional. Restricts input to the ASCII letters a-z and A-Z. This mask element is
?
equivalent to [a-zA-Z]? in regular expressions.
Character, required. If the AsciiOnly property is set to true, this element behaves like
&
the "L" element.
Character, optional. Any non-control character. If the AsciiOnly property is set to
C
true, this element behaves like the "?" element.
Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it
A
will accept are the ASCII letters a-z and A-Z.
Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it
a
will accept are the ASCII letters a-z and A-Z.
< Shift down. Converts all characters that follow to lowercase.
> Shift up. Converts all characters that follow to uppercase.

The following table shows example masks.

Mask Behavior
A date (day, numeric month, year) in international date format. The "/" character is a logical
00/00/0000 date separator, and will appear to the user as the date separator appropriate to the
application's current culture.
United States phone number, area code optional. If users do not want to enter the optional
(999)-000-
0000 characters, they can either enter spaces or place the mouse pointer directly at the position in
the mask represented by the first 0.

(2) BeepOnError: Gets or sets a value indicating whether the masked text box control raises the system
beep for each user key stroke that it rejects. If this property is set to true MaskedTextBox control should
beep on invalid input.
(3) TextMaskFornmat: The TextMaskFormat property determines how the literal and prompt
characters in the mask are processed when the generating the formatted string. More specifically, it
determines whether literal characters, prompt characters, or both are included in the Text property. When
prompt characters are excluded, they are transformed into spaces in the formatted string.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA

ExcludePromptAndLiterals Return only text input by the user.


IncludeLiterals Return text input by the user as well as any literal characters defined in
the mask.
IncludePrompt Return text input by the user as well as any instances of the prompt
character.
IncludePromptAndLiterals Return text input by the user as well as any literal characters defined in
the mask and any instances of the prompt character. ss

 Event: -
(1) MaskChange: Occurs after the input mask is changed. The MaskChanged event is raised after the
value of the Mask property is changed.
(2) MaskInputRejected: Occurs when the user's input or assigned character does not match the
corresponding format element of the input mask. MaskInputRejected is the default event for the
MaskedTextBox class.
The MaskInputRejected event occurs when a character is rejected by the input mask. The input mask,
represented by the Mask property

(22) LinkLabel Control:


What You Can Do with the LinkLabel Control?
The LinkLabel control is similar to a Label control with the exception that it can display a hyperlink.
Multiple hyperlinks can be specified in the text of the control. Each hyperlink can perform a different task
within an 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. You can also set part of the text as a link to a
file, folder, or Web page.

In addition to all the properties, methods, and events of the Label control, the LinkLabel control has
properties for hyperlinks and link colors. The LinkArea property sets the area of the text that activates the
link. The LinkColor, VisitedLinkColor, and ActiveLinkColor properties set the colors of the link. The
LinkClicked event determines what happens when the link text is selected.

You can also display multiple hyperlinks using the Links property. The Links property enables you
to access a collection of links. You can use the Add method of the LinkLabel.LinkCollection class by
accessing the collection through the Links property.

You can also specify data in the LinkData property of each individual Link object. The value of the
LinkData property can be used to store the location of a file to display or the address of a Web site.

 Property :-
(1) LinkBehavior: Gets or sets a value that represents the behavior of a link. The default is
LinkBehavior.SystemDefault.

AlwaysUnderline The link always displays with underlined text.


HoverUnderline The link displays underlined text only when the mouse is hovered over the link
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
text.
NeverUnderline The link text is never underlined. The link can still be distinguished from other
text by use of the LinkColor property of the LinkLabel control.
SystemDefault The behavior of this setting depends on the options set using the Internet
Options dialog box in Control Panel or Internet Explorer.
(2) LinkArea: Gets or sets the range in the text to treat as a link.
System.Windows.Forms.LinkArea (Start as Integer, Length as Integer)
For example 1:
Me.linkLabel1.LinkArea = New System.Windows.Forms.LinkArea (0, 8)
For example 2:
For On Line (Live Darshan) of Shridi SAI BABA click here : www.shrisaibabasansthan.org
LinkLabel2.LinkArea = New System.Windows.Forms.LinkArea(59, 27)

For example 3:
For On Line (Live Darshan) of SIDDHIVINAYAK, MUMBAI click here : www.siddhivinayak.org
LinkLabel3.LinkArea = New System.Windows.Forms.LinkArea(65, 21)

(3) LinkColor: Gets or sets the color used when displaying a normal link.A Color that represents the
color used to displaying a normal link. The default color is specified by the system, typically this color is
Color.Blue.
(4) LinkVisited: A LinkLabel control does not automatically denote that a link is a visited link. To
display the link as a visited link, you can set the value of this property to true in an event handler for the
LinkClicked event of a LinkLabel. A visited link is displayed using the color specified in the
VisitedLinkColor property of the LinkLabel control.You can set this property to true, to indicate it was
visited link.
(5) VisitedLinkColor : Gets or sets the color used when displaying a link that that has been previously
visited. The default color is specified by the system, typically this color is Color.Purple.
(6) Links: Gets the collection of links contained within the LinkLabel.
A LinkLabel control can display any number of links within the text of the control. This property
enables you to access the LinkLabel.LinkCollection instance associated with the LinkLabel that represents
the collection of links displayed in the control. You can then use the members of the
LinkLabel.LinkCollection class to add, remove, and find links in the collection.

 Event: -
(1) Linkclicked: Occurs when a link is clicked within the control.

(23) Form: -
The Form object in Visual Basic 6.0 is replaced by the Form class in Visual Basic 2005. In Visual
Basic 2005, the support for Windows forms is in the System.Windows.Forms namespace and the form
class is System.Windows.Forms.Form.

Forms are the main building blick of VB project. Forms are the windows on which controls are
placed. It is the “base” on which user interface is build.

A form represents a window or dialog box that makes up an application's user interface.
A Form is a representation of any window displayed in your application. The Form class can be used to
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
create standard, tool, borderless, and floating windows. You can also use the Form class to create modal
windows such as a dialog box. A special kind of form, the multiple-document interface (MDI) form, can
contain other forms called MDI child forms. An MDI form is created by setting the IsMdiContainer
property to true. MDI child forms are created by setting the MdiParent property to the MDI parent form
that will contain the child form.

 Property :-
(1) Name : (2) BackColor : (3) ForeColor : (4) Visible : (5) Enabled : (6) Height : (7) Width :
(8) Left : (9) Top : (10) Cursor : (11) TabStop :
(12) WindowState : Gets or sets the form's window state. This property determines the mode in which
the form is displayed. The default is FormWindowState.Normal.

Maximized A maximized window.


Minimized A minimized window.
Normal A default sized window.

(13) Text: Gets or sets the text associated with this control. It is the text that is display in the title bar of
the form.
(14) BackgroundImage: Gets or sets the background image displayed in the form.
(15) Icon: Gets or sets the icon for the form.
(16) AcceptButton: Gets or sets the button control (Name of button control) on the form that is clicked
when the user presses the ENTER key.
(17) CancelButton: Gets or sets the button control (Name of button control) that is clicked when the user
presses the ESC key.
(18) MdiParent: Gets or sets the current MDI parent form of this form.
To create an MDI child form, assign the Parent Form (that will be the MDI parent form) to the
MdiParent property of the child form.
Form1.MdiParent = Me
Form1.Show ()
(19) MdiChildren: Returns an array of forms that represent the MDI child forms that are parented to this
form. You can use this property to loop through all the MDI child forms to perform operations.
(20) IsMdiContainer: Gets or sets a value indicating whether the form is a container for MDI child
forms. By default value is Fasle. If this property is set to True, then this form will become container for
MDI child forms.
(20) IsMdiChild: Gets a value indicating whether the form is a an MDI child form. (True or False)
(21) Controls: Returns the collection of controls contained within the control.
When controls are added to a Form, each of the controls is a member of the Control.ControlCollection
assigned to the Controls property of the form, which is derived from the Control class
(22) DialogResult: Gets or sets the dialog result for the form. The DialogResult of a form is the value
that is returned from the form when it is displayed as a modal dialog box. It can be Cancel, Ignore, No,
None, OK, Retry, Yes.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(23) ShowInTaskbar: Gets or sets a value indicating whether the form is displayed in the Windows
taskbar. It it is set to true then, form is display in the Windows taskbar at run time. By default is True.
(24) ShowIcon: Gets or sets a value indicating whether an form’s icon is displayed in the caption bar
(title bar) of the form. By default is True.
(25) ControlBox: Gets or sets a value indicating whether a control box is displayed in the caption bar
(title bar) of the form. By default is True.
(26) MaximizeBox: Gets or sets a value indicating whether the Maximize button is displayed in the
caption bar (title bar) of the form. By default is True.
(27) MinimizeBox: Gets or sets a value indicating whether the Minimize button is displayed in the
caption bar (title bar) of the form. By default is True.
(28) FormBorderStyle: Gets or sets the border style of the form. The default is
FormBorderStyle.Sizable.

Fixed3D : A fixed, three-dimensional border.


FixedDialog : A thick, fixed dialog-style border.
FixedSingle : A fixed, single-line border.
FixedToolWindow : A tool window border that is not resizable. A tool window does not appear in the
taskbar or in the window that appears when the user presses ALT+TAB.
None : No border.
Sizable : A resizable border.
SizableToolWindow : A resizable tool window border. A tool window does not appear in the taskbar
or in the window that appears when the user presses ALT+TAB.
(29) Modal : Gets a value indicating whether this form is displayed modally.
It is read only property. You can use this property to determine whether a form has been displayed modally
or not.
(30) KeyPreview: Gets or sets a value indicating whether the form will receive key events before the
event is passed to the control that has focus.
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events.
After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to
the control with focus. For example, if the KeyPreview property is set to true and the currently selected
control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control
will receive the key that was pressed.
For example, when an application uses function keys, you might want to process the keystrokes at
the form level rather than writing code for each control that might receive keystroke events.

 Methods : -
(1) SetBound (2) BringToFront (3) SendToBack (4) Focus
(5) Activate : Activates the form and gives it focus. Activating a form brings it to the front if this is the
active application. The form must be visible for this method to have any effect.
(6) Close : Closes the form. For example: Me.Close()
(7) Show : Makes the form display by setting the visible property to true.
(8) ShowDialog : Shows the form as a modal dialog box.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(9) Hide : Hides the form.
(10) Dispose : Releases the resources used by the form.
(11) LayoutMdi : Arranges the multiple-document interface (MDI) child forms within the MDI parent
form.
ArrangeIcons : All MDI child icons are arranged within the client region of the MDI parent form.
Cascade : All MDI child windows are cascaded within the client region of the MDI parent form.
TileHorizontal : All MDI child windows are tiled horizontally within the client region of the MDI parent
form.
TileVertical : All MDI child windows are tiled vertically within the client region of the MDI parent
form.
For example: Me.LayoutMdi (MdiLayout.Cascade)

 Events: -
(1)Click,(2)DoubleClick,(3)MouseDown,(4)MouseEnter,(5)MouseHover,(6)MouseLeave,
(7)MouseMove, (8) MouseUp, (9) MouseWheel, (10) MouseClick, (11) MouseDoubleClick
(12)TextChanged,(13)KeyPress,(14)KeyDown,(15)KeyUp,(16)Enter,(17)Leave,(18)GotFocus,
(19)LostFocus, (20) Validating, (21) Validated
(22) Activated: Occurs when the form is activated in code or by the user.
(23) Deactivate: Occurs when the form loses focus and is not the active form.
(24) Closed: Occurs when the form is closed. This event occurs after the form has been closed by the user
or by the Close method of the form.

Note: The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead.

FormClosed: Occurs after the form is closed. The FormClosed event occurs after the form has been closed
by the user or by the Close method or the Exit method of the Application class.

Note: This event is new in the .NET Framework version 2.0.

(25) Closing: Occurs when the form is closing. The Closing event occurs as the form is being closed.
When a form is closed, all resources created within the object are released and the form is disposed. If you
cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the
CancelEventArgs passed to your event handler to true.

Note: The Closing event is obsolete in the .NET Framework version 2.0; use the FormClosing event
instead.

FormClosing : Occurs before the form is closed.

Note: This event is new in the .NET Framework version 2.0.

Example 1:
Private Sub Form1_Closing (sender As Object, e As System.ComponentModel.CancelEventArgs)
Handles MyBase.Closing
‘Determine if text has changed in the textbox by comparing to original text.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
If textBox1.Text <> strMyOriginalText Then
' Display a MsgBox asking the user to save changes or abort.
If MessageBox.Show ("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) = DialogResult.Yes Then
' Cancel the Closing event from closing the form.
e.Cancel = True
End If ' Call method to save file...
End If
End Sub 'Form1_Closing

Example 2:

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


system.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

If e.CloseReason = CloseReason.ApplicationExitCall Or e.CloseReason =


CloseReason.MdiFormClosing Or e.CloseReason = CloseReason.TaskManagerClosing Or
e.CloseReason = CloseReason.UserClosing Or e.CloseReason =
CloseReason.WindowsShutDown Then
Dim ans As Integer = MsgBox ("Do you want to exit?", MessageBoxButtons.YesNo, "Quit ?")
If ans = MsgBoxResult.Yes Then
Me.Close
Else
e.Cancel = True
End If
End If
End Sub
(26) ControlAded: Occurs when a new control is added to the Control.ControlCollection.
Control.ControlCollection Class : Represents a collection of Control objects.
(27) ControlRemoved: Occurs when a new control is removed from the Control.ControlCollection.
(28) Load: Occurs before a form is displayed for the first time.
(29) Move: Occurs when the control (form) is moved.
(30)Paint: Occurs when the control (form) is redrawn.
(31) Resize: Occurs when the control (form) is resized.

VB .NET File Extension in Visual Studio :


File Extension Description
.sln Solution File, storing the solution’s configuration. This contains one or more projects
(similar to VB6 group file).
.suo Contains user options for solution. (Stores Solution User Options)
.vbproj Represents a single project (A Visual Basic project), or all the files that are used to
create an assembly.
Vbproj.user Contains project level user options
.vb Contains source code (Form’s code file)
AssemblyInfo.vb General information about an assembly, including version information. The
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
AssemblyInfo.vb file contains extra information, or metadata, about your application
Bin Directory for binary executables.
Obj Derectory for debugging binaries.

 Procedure and function:-


 What is a procedure?
A procedure is a separate section of code which performs one or more specific tasks & is
identified by having a name.
OR A named sequence of statements executed as a unit.

 Advantages of procedures:-
1) Procedures allow you to break your program into small well-defined tasks, which you can debug
more easily than a program without procedures. (Easy to understand, Easy to Debug).
2) Avoid repeated task: - procedures are useful to avoid repeated task, ex. (frequently used calculation).
Code can be reuse.
3) You can use procedures in other program.
4) Easier to maintain. (Change can be made once in a procedure).

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Types of procedures: -
Visual Basic uses several types of procedures:
1) Sub-procedures.
2) Function procedures.
3) Event procedures. etc

(1) Sub Procedures: -


A Sub Procedures or general procedure is a block of code that is executed when it is called through
code. It performs actions but do not return a value to the calling code.

A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub
statements. Each time the procedure is called, its statements are executed, starting with the first executable
statement after the Sub statement and then returns control to the calling code, (when the End Sub, Exit
Sub, or Return statement encountered), but it does not return a value to the calling code.

You can define a Sub procedure in modules, classes, and structures. It is Public by default, which
means you can call it from anywhere in your application that has access to the module, class, or structure in
which you defined it.

The syntax for declaring a Sub procedure is as follows:

[Modifiers] Sub subprocedurename [(parameterlist)]


‘Statements of the Sub procedure.
End Sub

Calling Syntax: The syntax for a call to a Sub procedure is as follows:

[Call] subname [(argumentlist)]


Example:
Sub Add(x as integer, y as integer)
A=Val(x) + Val(y)
Msgbox (A)
End Sub
You can call above procedure is as follows
Call Add (776, 10)
OR
Add (776, 10)

(2) Function Procedures: -


Function procedure is similar to sub procedure but function procedure can return a value.
It returns a value by assigning it to the procedure name itself.

A Function procedure is a series of Visual Basic statements enclosed by the Function and End
Function statements. The Function procedure performs a task and then returns control to the calling code
(when the first End Function, Exit Function, or Return statement encountered). When it returns control, it
also returns a value to the calling code.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
You can define a Function procedure in a module, class, or structure. It is Public by default, which
means you can call it from anywhere in your application that has access to the module, class, or structure in
which you defined it.

The syntax for declaring a Function procedure is as follows:

[Modifiers] Function functionname [(parameterlist)] As returntype


‘Statements of the Function procedure.
Functionname = expression
OR
Return expression
End Function

Note: When you return a value by assigning a return value (expression) to the function name, then Control
does not return to the calling program until an Exit Function or End Function statement is executed.

Note: When you return a value by Return statement, then control is immediately return to the calling
program.

Calling Syntax: The syntax for a call to a Sub procedure is as follows:


Lvalue = functionname [(argumentlist)]

Example:
Function Add1(x as integer, y as integer) As integer
Ans= Val(x) + Val(y)
Add1 = Ans
End Function
You can call above procedure is as follows
MsgBox (Add1 (776, 10))

 Visual Basic Runtime Functions:-


The Visual Basic runtime provides many functions, located in the Microsoft.VisualBasic namespace.
These include such common functions as the Beep Function, MsgBox Function (Visual Basic), and StrComp
Function (Visual Basic). You call these functions the same way you call your own Function procedures.

 Passing Arguments:-
When variable is passed to a procedure, it is called an argument.
There are two ways of passing arguments to procedures.
1) Passing argument by value ( by default)
2) Passing argument by reference

1) Passing Arguments By Value. (ByVal)


When argument is passed by value, then two memory locations are involved. Means copy of variable
is passed, if the procedure changes the value, the change affects only the copy & original value of variable
remain as it is.
By default argument are passed by value (ByVal) in VB.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Example:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim S As Integer
S=4
ListBox1.Items.Add(S)
Twice(S)
ListBox1.Items.Add(S)
End Sub
------------------------------------------------------------------------------------
Sub Twice (ByVal Z As Integer)
Z=Z*2
ListBox1.Items.Add (Z)
End Sub
Output is as follows in the ListBox1
4
8
4

2) Passing Argument By reference.


When argument is passed by reference only one memory location is involved. Means address of
variable is passed to a procedure, As a result procedure can access to the original value of variable.

Example:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim S As Integer
S=4
ListBox1.Items.Add(S)
Twice(S)
ListBox1.Items.Add(S)
End Sub
------------------------------------------------------------------------------------
Sub Twice (ByRef Z As Integer)
Z=Z*2
ListBox1.Items.Add (Z)
End Sub

Output is as follows in the ListBox1


4
8
8

 Scope:-
Scope means which part of the application that can see & manipulate the element.
The scope of a declared element is the set of all code that can refer to it without qualifying its name
or making it available through an Imports Statement. An element can have scope at one of the following
levels:
Level Description

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Block scope Available only within the code block in which it is declared

Procedure scope Available to all code within the procedure in which it is declared

Module scope Available to all code within the module, class, or structure in which it is declared

Namespace scope Available to all code in the namespace in which it is declared

These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest
scope means the smallest set of code that can refer to the element without qualification. For more
information, see "Levels of Scope" on this page.

 Module:-
Declares the name of a module and introduces the definition of the variables, properties, events, and
procedures that the module comprises.

[ <attributelist> ] [ accessmodifier ] Module name


[ statements ]
End Module

 Parts:-
Attributelist
Optional. See Attribute List.
Accessmodifier
Optional. Can be one of the following:

 Public
 Friend

See Access Levels in Visual Basic.


Name
Required. Name of this module. See Declared Element Names.
Statements
Optional. Statements which define the variables, properties, events, procedures, and nested types of
this module.
End Module
Terminates the Module definition.

 Remarks: -

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Module statement defines a reference type available throughout its namespace. A module (sometimes
called a standard module) is similar to a class but with some important distinctions. Every module has
exactly one instance and does not need to be created or assigned to a variable. Modules do not support
inheritance or implement interfaces. Notice that a module is not a type in the sense that a class or structure is
you cannot declare a programming element to have the data type of a module.

You can use Module only at namespace level. This means the declaration context for a module must be
a source file or namespace, and cannot be a class, structure, module, interface, procedure, or block. You
cannot nest a module within another module, or within any type. For more information, see Declaration
Contexts and Default Access Levels.
A module has the same lifetime as your program. Because its members are all Shared, they also have
lifetimes equal to that of the program.
Modules default to Friend (Visual Basic) access. You can adjust their access levels with the access
modifiers. For more information, see Access Levels in Visual Basic.
All members of a module are implicitly Shared.

 Classes and Modules: -


These elements have many similarities, but there are some important differences as well.

 Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls
files) and standard modules (.bas files). The current version calls these classes and modules,
respectively.
 Shared Members. You can control whether a member of a class is a shared or instance member.
 Object Orientation. Classes are object-oriented, but modules are not. So only classes can be
instantiated as objects. For more information, see Classes vs. Modules.

Both classes and modules are reference types that encapsulate the items defined within, but they differ in
how items are accessed from other procedures.

 Differences between Classes and Modules:-


The main difference between classes and modules is that classes can be instantiated as objects while
standard modules cannot. Because there is only one copy of a standard module's data, when one part of your
program changes a public variable in a standard module, any other part of the program gets the same value if
it then reads that variable. In contrast, object data exists separately for each instantiated object. Another
difference is that unlike standard modules, classes can implement interfaces.

Note
When the Shared modifier is applied to a class member, it is associated with the class itself instead of a
particular instance of the class. The member is accessed directly by using the class name, the same way
module members are accessed. For more information about shared members, see Shared Members in Visual
Basic.

Classes and modules also use different scopes for their members. Members defined within a class are scoped
within a specific instance of the class and exist only for the lifetime of the object. To access class members
from outside a class, you must use fully qualified names in the format of Object.Member.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
On the other hand, members declared within a module are publicly accessible by default, and can be
accessed by any code that can access the module. This means that variables in a standard module are
effectively global variables because they are visible from anywhere in your project, and they exist for the
life of the program.

See Also
Reference
Shared (Visual Basic)

Concepts
Structures and Classes
Shared Members in Visual Basic

Other Resources
Understanding Classes

Rules
 Modifiers. All module members are implicitly Shared (Visual Basic). You cannot use the Shared
keyword when declaring a member, and you cannot alter the shared status of any member.
 Inheritance. A module cannot inherit from any type other than Object, from which all modules
inherit. In particular, one module cannot inherit from another.

You cannot use the Inherits Statement in a module definition, even to specify Object.

 Default Property. You cannot define any Default Properties in a module.

 Behavior:-
 Access Level. Within a module, you can declare each member with its own access level. Module
members default to Public (Visual Basic) access, except variables and constants, which default to
Private (Visual Basic) access. When a module has more restricted access than one of its members,
the specified module access level takes precedence.
 Scope. A module is in scope throughout its namespace.

The scope of every module member is the entire module. Notice that all members undergo type
promotion, which causes their scope to be promoted to the namespace containing the module. For
more information, see Type Promotion.

 Qualification. You can have multiple modules in a project, and you can declare members with the
same name in two or more modules. However, you must qualify any reference to such a member
with the appropriate module name if the reference is from outside that module. For more
information, see Resolving a Reference When Multiple Variables Have the Same Name.

Example:-

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Visual Basic
Copy Code
Public Module thisModule
Sub Main()
Dim userName As String = InputBox("What is your name?")
MsgBox("User name is" & userName)
End Sub
' Insert variable, property, procedure, and event declarations.
End Module

See Also
Scope
The scope of a declared element is the set of all code that can refer to it without qualifying its name or
making it available through an Imports Statement. An element can have scope at one of the following levels:
Level Description

Block scope Available only within the code block in which it is declared

Procedure scope Available to all code within the procedure in which it is declared

Module scope Available to all code within the module, class, or structure in which it is declared

Namespace scope Available to all code in the namespace in which it is declared

These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest
scope means the smallest set of code that can refer to the element without qualification. For more
information, see "Levels of Scope" on this page.

 Specifying Scope and Defining Variables:-


You specify the scope of an element when you declare it. The scope can depend on the following factors:

 The region (block, procedure, module, class, or structure) in which you declare the element
 The namespace containing the element's declaration
 The access level you declare for the element

Use care when you define variables with the same name but different scope, because doing so can lead to
unexpected results. For more information, see Resolving a Reference When Multiple Variables Have the
Same Name.

 Levels of Scope:-
A programming element is available throughout the region in which you declare it. All code in the same
region can refer to the element without qualifying its name.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Block Scope
A block is a set of statements enclosed within initiating and terminating declaration statements, such as the
following:

 Do and Loop
 For [Each] and Next
 If and End If
 Select and End Select
 SyncLock and End SyncLock
 Try and End Try
 While and End While
 With and End With

If you declare a variable within a block, you can use it only within that block. In the following example, the
scope of the integer variable cube is the block between If and End If, and you can no longer refer to cube
when execution passes out of the block.
Copy Code
If n < 1291 Then
Dim cube As Integer
cube = n ^ 3
End If

Note
Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you
enter the block more than once during the procedure, each block variable retains its previous value. To avoid
unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.

 Procedure Scope:-
An element declared within a procedure is not available outside that procedure. Only the procedure that
contains the declaration can use it. Variables at this level are also known as local variables. You declare
them with the Dim Statement (Visual Basic), with or without the Static (Visual Basic) keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure but outside any
block within that procedure, you can think of the variable as having block scope, where the block is the
entire procedure.

Note
All local elements, even if they are Static variables, are private to the procedure in which they appear. You
cannot declare any element using the Public (Visual Basic) keyword within a procedure.

 Module Scope:-
For convenience, the single term module level applies equally to modules, classes, and structures. You can
declare elements at this level by placing the declaration statement outside of any procedure or block but
within the module, class, or structure.
When you make a declaration at the module level, the access level you choose determines the scope. The
namespace that contains the module, class, or structure also affects the scope.
Elements for which you declare Private (Visual Basic) access level are available to every procedure in that
module, but not to any code in a different module. The Dim statement at module level defaults to Private if
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
you do not use any access level keywords. However, you can make the scope and access level more obvious
by using the Private keyword in the Dim statement.
In the following example, all procedures defined in the module can refer to the string variable strMsg.
When the second procedure is called, it displays the contents of the string variable strMsg in a dialog box.
Copy Code
‘Put the following declaration at module level (not in any procedure).
Private strMsg As String
‘Put the following Sub procedure in the same module.
Sub initializePrivateVariable()
StrMsg = "This variable cannot be used outside this module."
End Sub
‘Put the following Sub procedure in the same module.
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub

 Namespace Scope:-
If you declare an element at module level using the Friend (Visual Basic) or Public (Visual Basic) keyword,
it becomes available to all procedures throughout the namespace in which the element is declared. With the
following alteration to the preceding example, the string variable strMsg can be referred to by code
anywhere in the namespace of its declaration.
Copy Code
‘Include this declaration at module level (not inside any procedure).
Public strMsg As String

Namespace scope includes nested namespaces. An element available from within a namespace is also
available from within any namespace nested inside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the same
namespace. In this case, namespace scope can be thought of as project scope. Public elements in a module,
class, or structure are also available to any project that references their project.

 Choice of Scope:-
When you declare a variable, you should keep in mind the following points when choosing its scope.

 Advantages of Local Variables


Local variables are a good choice for any kind of temporary calculation, for the following reasons:

 Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you
can create several different procedures containing a variable called intTemp. As long as each
intTemp is declared as a local variable, each procedure recognizes only its own version of
intTemp. Any one procedure can alter the value in its local intTemp without affecting
intTemp variables in other procedures.

 Memory Consumption. Local variables consume memory only while their procedure is running.
Their memory is released when the procedure returns to the calling code. By contrast, Shared (Visual
Basic) and Static (Visual Basic) variables consume memory resources until your application stops
running, so use them only when necessary. Instance variables consume memory while their instance
continues to exist, which makes them less efficient than local variables, but potentially more efficient
than Shared or Static variables.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
 Minimizing Scope
In general, when declaring any variable or constant, it is good programming practice to make the scope as
narrow as possible (block scope is the narrowest). This helps conserve memory and minimizes the chances
of your code erroneously referring to the wrong variable. Similarly, you should declare a variable to be
Static (Visual Basic) only when it is necessary to preserve its value between procedure calls.

See Also

 Array & Collection:-


 Array :
An array is a group of common element accessed under a common name. Each element is referenced
with a no, called an index. In VB index start with zero.

When you use arrays, you can refer to multiple values by the same name, using a number called an
index or subscript to distinguish them from one another.

Characteristics of array
1) Array element (index) start with zero (0)
2) A object array may have different data type in each element.
3) Array may be fixed size or dynamically allocated at runtime.

 Fixed size Array :


You declare an array variable the same way as any other variable, using the Dim statement.

Dim Stud (5) As Integer

Stud array have been declared to hold 6 elements (0 to 5).


MsgBox (LBound (Stud)) 0 is the lower bound of this array
MsgBox (UBound (Stud)) 5 is the upper bound of this array

Note: In .NET Lower bound of array is always zero. So Option Base 1 statement is no longer exists.

 Array Dimensions : Multidimensional Array :-


The array Stud in the preceding example uses one index and is said to be one-dimensional. An array
that uses more than one index or subscript is called multidimensional.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
In your declaration, add one pair of parentheses after the variable name and place commas inside the
parentheses to separate the dimensions. The following example declares a variable to hold a two-
dimensional array with elements of the Short Data Type (Visual Basic).

 Ex:- To store 10 students Rollno with their Marks.


Dim Marks(9,9) As Short

 Ex. Of Three Dimension Array


Dim matrix(3, 0 To 9, 0 To 14)
0 to 3 = 4
0 to 9 = 11
0 to 14 = 15
4 * 11 * 15 = 660 Elements.

 Dynamic Array : -
If you do not know the size of array during the declaration of the array, then you can use dynamic
Array. You can declare the array as dynamic with empty parentheses (without dimension subscripts). You
can change the size of the array at run time (dynamically). It is called dynamic array. Dynamic array can be
resized at run time.
Ex.
Dim MyArray() As String
Then you can allocate actual no of element with a ReDim statement
ReDim MyArray (x + 1)
The ReDim statement is used to size or resize a dynamic array that has already been formally
declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).
You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
Note: ReDim statement can not change the dimension of the array.

When you use ReDim statement VB will completely erase the array & re-dimension it to the size you
specify.
Sometimes you may want to change the size of the array without losing the data in array, then you
can use Preserve Keyword with Redim statement.

You can also initialize the data in array if you don’t give an array an explicit size. In following dynamic
array example, we are initializing an array with the values “OM”, “DATAR”, & “MALIK”.
Dim MyArray () = {“OM”, “DATAR”, “MALIK”}
In above example we have not give the size of the array, so it is possible to initializing an array.

 Example of ReDim & Preserve


Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim x() As Integer ‘Dynamic Array
ReDim x(5) '0 to 5
For I As Integer = 1 To 5
x(I) = I
Next I
ReDim Preserve x(10)
For I As Integer = 6 To 10
x(I) = I
Next I
For I As Integer = 1 To 10
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
ListBox1.Items.Add(x(I))
Next I
End Sub

 Array related Functios :-


 IsArray Function: Returns a Boolean value indicating whether a variable is an array.
For example
Dim MyArray(4) As Integer
MsgBox(IsArray(MyArray)) ‘Returns True

 LBound Function: The lower bound for any dimension is always 0.


For example
Dim matrix (3, 0 To 9, 0 To 14)
MsgBox (LBound (matrix, 1)) ‘Here second argument is optional, which is the dimension
‘Returns 0
 UBound Function: The lower bound for any dimension is always 0.
For example
Dim matrix (3, 0 To 9, 0 To 14)
‘Here second argument is optional, which is the dimension
MsgBox (UBound (matrix, 1)) ‘Returns 3
MsgBox (UBound (matrix, 2)) ‘Returns 9
MsgBox (UBound (matrix, 3)) ‘Returns 14

 Collection : -
Introduction:
In dynamic array ReDim takes up more execution time, because it actually creates a new array of the
specified size which replaces the existing array. If you have specified a Preserve option. It also copies the
elements from the old array to new one. So, if you ReDim the arrays in your application frequently, its
performance would be hit considerably.

.NET provides you with a solution to this problem in the form of collections. Collections are better
optimized to handle size changes on the fly. They are different from arrays in one following respect.

 You don’t have to re-allocate memory as number of objects to hold increases. (ArrayList
collection provides you with an ideal alternative to arrays with optimized allocation / de-allocation
capabilities.)

 Other advantages of ArrayList and other collection classes in System.Collections namespace have
over the primitive array are the common operations (methods) that you get pre-coded in the forms of
methods (in built methods). For example ArrayList and other collection classes have in built methods like
Sort, Reverse, Search, Find, Add, Remove, Clear etc.

Although collections are most often used for working with the Object Data Type, you can use a
collection to work with any data type. In some circumstances, it can be more efficient to store items in a
collection than in an array.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
If you need to change the size of an array, you must use the ReDim Statement (Visual Basic). When
you do this, Visual Basic creates a new array and releases the previous array for disposal. This takes
execution time. Therefore, if the number of items you are working with changes frequently, or you cannot
predict the maximum number of items you need, you might obtain better performance using a collection.

In VB window form maintains a collection of all the controls on it using the Controls property
which is of type ControlCollection. ControlCollection is a collection class defined in
System.Windows.Form.Control nameplace.

(1) Visual Basic collection


(2) .NET Framework collection classes defined in the System.Collections namespace. They are not
strongly typed
(3) .NET Framework collection classes defined in the System.Collections.Generic namespace contains
interfaces and classes. Which allow users to create strongly typed collections that provide better type
safety and performance than non-generic strongly typed collections.
(4) .NET Framework collection classes defined in the System.Collections.Specialized namespace.

.NET Framework provides several alternatives to the Visual Basic collection. .NET framework
provides you with a variety of collection classes to serve various purposes. Some of the most useful
collection classes are defined in the System.Collections namespace & they are as follows. They all handle
allocation / de-allocation & size changes for you.
ArrayList Class, BitArray, HashTable, Queue, SortedList, Stack

Collection class in the System.Collections namespace, they are not strongly typed. These collection
classes store objects in them, a lot of data type conversion takes place every time you add or retrieve
something to / from them, which takes up a lot of execution time. The System.Collections.Generic
namespace contains interfaces and classes that define generic collections, which allow users to create
strongly typed collections that provide better type safety and performance than non-generic strongly typed
collections. In which List class has all those functions that you would fine in the ArrayList, and same goes
for other classes in System.Collections.Generic.
.NET framework provides you with a variety of following collection classes to create generic
collection.
List, LinkedList, Dictionary, Queue, SortedDictionary, SortedList, Stack

 Collection:
A Visual Basic Collection is an ordered set of items that can be referred to as a unit.
It is a lists of items grouped under a common name. Collections are more powerful than arrays, because they
have properties & methods attached to them & they can handle. And you don’t have to re-allocate memory
as number of objects to hold increases or decreases.

A collection is an object used for grouping and managing related objects. A collection is a way of
grouping a set of related items. Many different types of collections exist. Predefined collections are used in
Visual Basic applications for many purposes, For example, every Form has a collection of controls. (You
can access this collection through the form's Controls property.) The entire set of objects on a form is
called the Controls collection. The controls collection is created automatically when you open a new form,
and when you add objects to the form.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
The Visual Basic Collection object provides a convenient way to refer to a related group of items as
a single object. Elements or items of a collection do not have to share the same data type
You can also create your own collections to organize and manipulate objects. Collections are a good
way to keep track of objects that your application might need to dynamically create and destroy.
You can create a collection the same way you create other objects, as the following example
illustrates. The following example creates a new Visual Basic collection and assigns it to the variable coll

Dim coll As New Microsoft.VisualBasic.Collection ()


This Collection object is one-based, which means that the index values of the elements range from 1
through the value of the Count property. Visual Basic collections hold elements of type Object.
Once you have created a collection, you can do any of the following:

 Add an element with the Add Method.


 Remove an element with the Remove Method.
 Remove all elements with the Clear Method.
 Find out how many elements the collection contains with the Count Property.
 Check whether a specific element is present with the Contains Method.
 Return a specific element from the collection with the Item Property.
 Iterate through the entire collection with the For Each...Next Statement (Visual Basic).

Visual Basic collections are not compatible with the .NET Framework collections available in the
System.Collections, System.Collections.Generic, and System.Collections.Specialized namespaces.

 Methods : -
(1) Add: Adds an element to a Collection object.
Add(ByVal Item As Object, Optional ByVal Key As String,
Optional ByVal { Before | After } As Object = Nothing)

 Parameters:-
Item: Required. An object of any type that specifies the element to add to the collection.
Key : Optional. The Key argument is optional in a Visual Basic collection. A unique String expression
that specifies a key string that can be used instead of a positional index to access this new element in the
collection.
Before: Optional. An expression that specifies a relative position in the collection.

Example: -
Dim sampleVisualBasicColl As New Microsoft.VisualBasic.Collection ()

The collection in sampleVisualBasicColl can accept items of any data type.


Use the Add Method (Collection Object) to add elements to the collection. The following example
creates four String elements and adds them to the collection. It creates a unique String value as
the key for each new element and passes this value to the Add method.

Dim item1, item2, item3, item4 As String


item1 = "Items"
item2 = "In"
item3 = "A"
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
item4 = "Collection"
sampleVisualBasicColl.Add (item1, "firstkey")
sampleVisualBasicColl.Add (item2, "secondkey")
sampleVisualBasicColl.Add (item3, "thirdkey")
sampleVisualBasicColl.Add (item4, "fourthkey")
(2) Remove: Removes an element from a Collection object. Note that when an element is removed from a
Visual Basic Collection, the index values are renumbered from 1 through the value of the Count Property
(Collection Object).
Remove (ByVal {Key As String | Index As Integer})

 Parameters:-
Y: A unique String expression that specifies a key string that can be used, instead of a positional index, to
access an element of the collection. Key must correspond to the Key argument specified when the element
was added to the collection.
Index: A numeric expression that specifies the position of an element of the collection. Index must be a
number from 1 through the value of the collection's Count Property (Collection Object).

This example illustrates the use of the Remove method to remove objects from a Collection Object
(Visual Basic) in the variable birthdays.

' Remove the first element of the Visual Basic collection.


sampleVisualBasicColl.Remove (1)
' Remove the element with the key "secondkey".
sampleVisualBasicColl.Remove ("secondkey")
(3) Clear: Deletes all elements of a Visual Basic Collection object. The Clear method empties the
collection and resets its Count property to 0.
sampleVisualBasicColl.Clear()

(4)Contains: Returns a Boolean value indicating whether a Visual Basic Collection object contains an
element with a specific key.
Public Function Contains (ByVal Key As String) As Boolean

Key: Required. A String expression that specifies the key for which to search the elements of the
collection.

Example:
Dim customers As New Microsoft.VisualBasic.Collection ()
Dim accountNumber As String = "1234"
' Insert code that obtains new customer objects.
' Use the new customer's account number as the key.
customers.Add (newCustomer, accountNumber)
' The preceding statements can be repeated for several customers.
Dim searchNumber As String = "1234"
' Insert code to obtain an account number to search for.
If customers.Contains (searchNumber) Then
MsgBox ("The desired customer is in the collection.")
Else
MsgBox ("The desired customer is not in the collection.")
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
End If

 Property :-
(1) Count: Returns an Integer containing the number of elements in a collection. Read-only.
Dim birthdays As New Collection ()
birthdays.Add (New DateTime (2001, 1, 12), "Bill")
birthdays.Add (New DateTime (2001, 1, 13), "Joe")
birthdays.Add (New DateTime (2001, 1, 14), "Mike")
birthdays.Add (New DateTime (2001, 1, 15), "Pete")
……
........
MsgBox ("Number of birthdays in collection: " & CStr(birthdays.Count))
The Collection object is one-based, which means that the index values of the elements range from 1 through
the value of the Count property.
(2) Item: Returns a specific element of a Collection object either by position or by key. Read-only.
Default Public ReadOnly Property Item (ByVal {Key As String | Index As Integer | Index As Object}
) As Object
The Item property is the default property for a collection. Therefore, the following lines of code are
equivalent.
MsgBox (CStr (customers.Item (1)))
MsgBox (CStr (customers (1)))

Example:-
Dim birthdays As New Collection ()
birthdays.Add (New DateTime (2001, 1, 12), "Bill")
birthdays.Add (New DateTime (2001, 1, 13), "Joe")
birthdays.Add (New DateTime (2001, 1, 14), "Mike")
birthdays.Add (New DateTime (2001, 1, 15), "Pete")

...

Dim aBirthday As DateTime


ABirthday = birthdays.Item ("Bill")
MsgBox (CStr (aBirthday))

For Each...Next Statement:-


Repeats a group of statements for each element in a collection or array. You can use a For Each loop to
iterate through every element of a collection or array.

For Each element [As datatype] In group


[Statements]
[Exit For]
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
[Statements]
Next [element]

 Element: Required in the For Each statement. Optional in the Next statement. Variable. Used to
iterate through the elements of the collection.
 Datatype: Required if element is not already declared. Data type of element.
 Group: Required. Object variable. Refers to the collection over which the statements are to be
repeated.
 Statements: Optional. One or more statements between For Each and Next that run on each item
in group.
 Exit For: Optional. Transfers control out of the For Each loop.
 Next: Required. Terminates the definition of the For Each loop.
Example: 1
‘Declare an array
Dim StudArr (4) As String

‘Store the data


StudArr (0) = “Om”
StudArr (1) = “Shivangi”
StudArr (2) = “Priyam”
StudArr (3) = “Bhaskar”
StudArr (4) = “Jayani”

‘Following For Each……Next loop iterate through a string collection, in this example, it is used in an
‘array. You have to create a control variable that is of the same type as an element in the array
‘(Studname) & gives this to the loop when it starts. You can search as follows

For Each Studname As String In StudArr


If Studname = "Priyam" Then
MsgBox("Found")
End If
Next

‘ OR you can add all the elements of array to the ListBox1


For Each Studname As String In StudArr
ListBox1.Items.Add(StudName)
Next

Example: 2
Use a For Each...Next Statement (Visual Basic) to examine each element of the collection. The following
example searches for a particular string and displays it if found.
For Each aString in sampleVisualBasicColl
If aString = "Collection" Then
MsgBox(aString)
End If
Next aString
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or
array.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
A For...Next Statement (Visual Basic) works well when you can associate each iteration of a loop with a
control variable and determine that variable's initial and final values. However, when you are dealing with a
collection, the concept of initial and final values is not meaningful, and you do not necessarily know how
many elements the collection has. In this case, a For Each...Next loop is a better choice.
You can display, move, sort, rename or resize an entire collection of objects at once For Each...Next
statement is used.

 ArrayList:-
An ArrayList is a kind of collection, which .NET Framework uses extensively.
ArrayList collection provides you with an ideal alternative to arrays with optimized allocation / de-
allocation capabilities (optimized for on-the-fly size changes means whose size is dynamically increased as
required). Other advantages of ArrayList and other collection classes in System.Collections namespace have
over the primitive array are the common operations (methods) that you get pre-coded in the forms of
methods (in built methods). For example ArrayList and other collection classes have in built methods like
Sort, Reverse, Search, etc.
.NET Framework provides several alternatives to the Visual Basic collection. .NET framework
provides you with a variety of collection classes to serve various purposes & defined in the
System.Collections namespace.

 Property :-
(1) Count: Gets the number of elements actually contained in the ArrayList.
(2) IsFixedSize: Gets a value indicating whether the ArrayList has a fixed size.
(3) IsReadOnly: Gets a value indicating whether the ArrayList is read-only.
(4) Item: Gets the element at the specified index.

 Methods : -
(1) Add: Adds an object to the end of the ArrayList.
(2) AddRange: Adds the elements of an ICollection to the end of the ArrayList.
(3) Insert: Inserts an element into the ArrayList at the specified index.
(4) InsertRange: Inserts the elements of a collection into the ArrayList at the specified index.
(5) Remove: Removes the first occurrence of a specific object from the ArrayList.
(6) RemoveRange: Removes a range of elements from the ArrayList.
(7) RamoveAt: Removes the element at the specified index of the ArrayList.
(8) IndexOf: Returns the zero-based index of the first occurrence of a value in the ArrayList or in a
portion of it.
(9) BinarySearch: Uses a binary search algorithm to locate a specific element in the sorted ArrayList or
a portion of it.
(10) Clear: Removes all elements from the ArrayList.

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
(11) Contains: Determines whether an element is in the ArrayList.
(12) Reverse: Reverses the order of the elements in the ArrayList or a portion of it.
(13) Short: Sorts the elements in the ArrayList or a portion of it.
(14) ToArray: Copies the elements of the ArrayList to a new array.

 Example of ArrayList class:-


‘First declare the object of ArrayList class.
Dim MyAL As ArrayList
‘You don’t have to specify the size of the collection at the time of creating the collection objects, as they ‘as
capable of growing as needed. But you have an option of specifying the size of the collection, if you ‘know
the required capacity.
MyAL = new ArrayList(VarItem)
OR
' Creates and initializes a new ArrayList.
Dim MyAL As New ArrayList()
‘Adding items to the collections
MyAL.Add(“OM”)
MyAL.Add(“PRIYAM”)
MyAL.Add(“DATTAVI”)
MyAL.Add(“SHIVANI”)
MyAL.Add(“SURAJ”)
MyAL.Add(“JAYANI”)
‘Procedure to load the data of ArrayList to the ListBox1
Sub LoadArrList()
ListBox1.Items.Clear()
For i As Integer = 0 To myAL.Count - 1
ListBox1.Items.Add(myAL(i))
Next
End Sub

OR
ListBox1.Items.Clear()
Dim obj As [Object]
For Each obj In MyAL
ListBox1.Items.Add(obj)
Next obj
‘ Sorting the ArrayList objects can be very simple with the sort method of ArrayList class.
MyAL.Sort()
ListBox1.Items.Clear()
LoadArrList()
‘Searching the ArrayList objects can be very simple with the methods like ContainsValue, IndexOf,
‘Contains, Find, etc
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Dim StrName As String = InputBox("Please enter the name to Search from the ArrayList Collection")
If myAL.Contains(StrName) = True Then
MsgBox("GIVEN NAME HAS BEEN FOUND IN THE COLLECTION")
Else
MsgBox("GIVEN NAME HAS NOT BEEN FOUND IN THE COLLECTION")
End If
‘Searching the Index Of the selected name from the ListBox1
If ListBox1.SelectedItem Is Nothing Then
MsgBox(“Please select the name form the list box to search”)
Else
MsgBox(“Index of the selected name is “ & MyAL.IndexOf(ListBox1.SelectedItem).ToString)
End If
‘Reversing
MyAL.Reverse ()
ListBox1.Items.Clear ()
LoadArrList ()
‘Removing from ArrayList collection
MyAL.Remove (“DATTAVI”)

' OR Removes the element at index 5.


MyAL.Remove (2)
‘ OR Removes three elements starting at index 4.
MyAL.RemoveRange (Starding_Index, No_Of_elements_To_Remove)
MyAL.RemoveRange (2,3)
An ArrayList or List object is a sophisticated version of an array. The ArrayList class and the List generic
class provides some features that are offered in most System.Collections classes but are not in the Array
class.
For example:

 The capacity of an Array is fixed, whereas the capacity of an ArrayList or a List is automatically
expanded as required. If the value of the Capacity property is changed, the memory reallocation and
copying of elements are automatically done.
 ArrayList and List provide methods that add, insert, or remove a range of elements. In Array, you
can get or set the value of only one element at a time.
 A synchronized version of ArrayList or List is easy to create using the Synchronized method. The
Array class leaves it up to the user to implement synchronization.
 ArrayList and List provide methods that return read-only and fixed-size wrappers to the collection.
Array does not.

On the other hand, Array offers some flexibility that ArrayList and List do not. For example:

 You can set the lower bound of an Array, but the lower bound of an ArrayList or a List is always
zero.
 An Array can have multiple dimensions, while an ArrayList or a List always has exactly one
dimension.
 An Array of a specific type (other than Object) has better performance than an ArrayList because
the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
when storing or retrieving a value type. However, a List can have similar performance to an array of
the same type if no reallocations are required; that is, if the initial capacity is a good approximation
of the maximum size of the list.

Most situations that call for an array can use an ArrayList or a List instead; they are easier to use and, in
general, have performance similar to an array of the same type.
Array is in the System namespace; ArrayList is in the System.Collections namespace; List is in the
System.Collections.Generic namespace.

Public Class Form1


' Creates and initializes a new ArrayList.
Dim myAL As New ArrayList()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
myAL.Add("OM")
myAL.Add("PRIYAM")
myAL.Add("DATTAVI")
myAL.Add("SHIVANI")
myAL.Add("SURAJ")
myAL.Add("JAYANI")
End Sub
Sub LoadArrList()
ListBox1.Items.Clear()
For i As Integer = 0 To myAL.Count - 1
ListBox1.Items.Add(myAL(i))
Next
End Sub
'cODING OF LOAD DATA BUTTON
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
LoadArrList()
End Sub

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


System.EventArgs) Handles Button2.Click
myAL.Sort()
ListBox1.Items.Clear()
LoadArrList()
End Sub

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


System.EventArgs) Handles Button3.Click
If ListBox1.SelectedItem Is Nothing Then
MsgBox("Please select the name form the list box to search")
Else
MsgBox("Index of the selected name is " &
myAL.IndexOf(ListBox1.SelectedItem).ToString)
End If
End Sub

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


System.EventArgs) Handles Button4.Click
myAL.Reverse()
ListBox1.Items.Clear()
LoadArrList()

End Sub

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


System.EventArgs) Handles Button5.Click
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
Dim n As String = InputBox("Please enter the name to search")
If myAL.Contains(n) = True Then
MsgBox("GIVEN NAME HAS BEEN FOUND IN THE COLLECTION")
Else
MsgBox("GIVEN NAME HAS NOT BEEN FOUND IN THE COLLECTION")
End If

End SubEnd Class

Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy