VB.Net
VB.Net
(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.
(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).
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.
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
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.
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) < (Ø = ø)
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.
On other hand, if we import the System.Console namespace, that makes the namespace immediately
available. WriteLine (“Faith Brings The Pure Megic”)
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.
End Sub
OpenFileDialog1.ShowDialog()
RTB1.LoadFile(OpenFileDialog1.FileName)
End Sub
End Sub
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.
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:
You can find the possible constants to use for the Buttons argument as follows. (The MsgBoxStyle
enumeration values are as follows).
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.
MsgBoxSetForeground 65536 Specifies the message box window as the foreground window.
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.
Example:
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.
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.
The result of the Show method is a value from the DialogResult enumeration, showing what button
the user clicked:
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.
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.
(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.
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.
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 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.
[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"
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.
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.
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.
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.
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.
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.
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.)
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
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.
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.
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:
Example:
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:
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:
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."
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)
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.
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.
The following modifiers are used to control how properties and methods are overridden:
Example:
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
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
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:
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
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
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
End Class
‘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.
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.
‘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:
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:
Now I can create a new object of the employee class named Edward:
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.
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:
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:
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.
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..
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:
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.)
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.
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.
Namespace: System.Windows.Forms
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.
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
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.
(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)
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)
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.
(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.
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)
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.
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]
V.S.PATEL BCA COLLEGE, BILIMORA
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.
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
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.
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.
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)
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 : -
(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.
(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.
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.
(2) ItemCheck: This event is triggered when the checkedstate of the item is changed.
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.
(2) DropDownStyleChanged: It occurs when the value of the DropDownStyle property has changed.
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).
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.
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.
(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.
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.
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:
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.
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.
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)
(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.
(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.
Using the Mask property, you can specify the following input without writing any custom validation
logic in your application:
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.
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
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
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.
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.
(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.
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.
(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.
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:
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
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.
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.
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.
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))
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
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
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
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.
Parts:-
Attributelist
Optional. See Attribute List.
Accessmodifier
Optional. Can be one of the following:
Public
Friend
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.
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.
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.
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
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.
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.
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
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.
Note: In .NET Lower bound of array is always zero. So Option Base 1 statement is no longer exists.
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).
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.
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.
.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
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 ()
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.
(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")
...
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
‘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
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.
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”)
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.
End Sub
Dr.Krunal Bhavsar
[Ph.D in CS,MCA,B.Sc,CCNA,DCA,Ele.tech]