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

Unit-3-3

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

Unit-3-3

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

SDJ International College, Palsana

Unit – 3 Introduction to Windows Controls


3.1 Working with Tool Box Controls

Every .NET control consists of three important elements:


1. Properties which describe the object,
2. Methods cause an object to do something and
3. Events are what happen when an object does something.

Properties:
All the .NET Objects can be moved resized or customized by setting their
properties. A property is a value or characteristic held by a .NET object, such as
Caption or ForeColor. Properties can be set at design time by using the Properties
window or at run time by using statements in the program code.

Methods:
A method is a procedure created as a member of a class and they cause an object to
do something. Methods are used to access or manipulate the characteristics of an
object or a variable. There are mainly two categories of methods you will use in
your classes:
 If you are using a control such as one of those provided by the Toolbox, you
can call any of its public methods. The requirements of such a method
depend on the class being used.
 If none of the existing methods can perform your desired task, you can add a
method to a class.

Events:
An event is a signal that informs an application that something important has
occurred. For example, when a user clicks a control on a form, the form can raise a
Click event and call a procedure that handles the event. There are various types of
events associated with a Form like click, double click, close, load, resize, etc.

FORM:
 VB.NET Form is the container for all the controls that make up the user
interface.
 Every window you see in a running visual basic application is a form,
adding controls and other items from the toolbox.
 In VB.NET, the support for windows forms is in the System.Window.Forms
namespace and the form class is System.Windows.Form.

Prepared By Prof. Hemanta Bhatt Page 1


SDJ International College, Palsana

 The form class itself is based on the Control class, which means that forms
share a lot of the properties and methods that control do.
 The main area of a form- the area where everything takes place- is called the
client area.
 In general, Visual Basic code works with controls in the client area and
leaves the rest of the form to Visual Basic.

Form Properties:
Following lists down various important properties related to a form. These
properties can be set or read during application execution.

AcceptButton: Gets or sets the button on the form that is pressed when the user
uses the Enter key.
ActiveMidChild: Gets the currently active multiple document interface (MDI)
child window.
AllowDrop: Indicates if the form can accept data that the user drags and drops into
it.
AutoScale: Indicates if the form adjust its size to fit the height of the font used on
the formand scales its controls.
AutoScroll: Indicates if the form implements auto scrolling.
BackColor: Gets or sets the background color for this form.
BackgroundImage: Gets or sets the background image in the form.
Bottom: Gets the location of the bottom of the form.
Bounds: Gets or sets the bounding rectangle for the form.
Enabled: Gets or sets a value indicating if the form is enabled.
Focused: Indicates if the form has input focus.
ForeColor: Gets or sets the foreground color of the form.
FormBorderStyle: Gets or sets the border style of the form.
Height: Gets or sets the height of the form.
IsMdiChild: Indicates if the form is an MDI child form.
IsMdiContiner: Gets or sets a value indicating if the form is a container for MDI
child forms.
MaximizeBox: Gets or sets a value indicating if the maximize button is displayed
in the captionbar of the form.
MaximizeSize: Returns the maximum size the form can be resized to.
MdiChildren: Return an array of forms of the MDI child forms that are parented
to this form.
MdiParent: Gets or sets the current MDI parent form of this form.
Menu: Gets or sets the Main Menu that is displayed in the form.

Prepared By Prof. Hemanta Bhatt Page 2


SDJ International College, Palsana

MinimizeBox: Gets or sets a value indicating if the minimize button is displayed


in the captionbar of the form.
MinimumSize: Gets the minimum size the form can be resized to.
Name: Gets or sets the name of the form.
Size: Gets or sets the size of the form.
StartPosition: Gets or sets the starting position of the form at run time.
Text: Gets or sets the text associated with this form.
Visible: Gets or sets a value indicating if the form is
visible.Width: Gets or sets the width of the form.
WindowState: Gets or sets the form’s window state.

Form Methods:
The following are some of the commonly used methods of the Form class:

Activate Active the form (gives it focus makes it active).


BringToFront Brings the form to the front of the stacking order.
Close Closes the form.
Contains Indicates if the specified control is a child of this form.

Dispose Release the resources used by the form.


DoDragDrop Begins a drag-and-drop operation.
Focus: Gives the form the focus.
GetChildAtPoint: Gets the child control that is located at the specified
coordinates.

GetNextControl Gets the next control in the tab order of child controls.

Hide Hides the form.


LayoutMdi Arranges the MDI child forms within the MDI parent form.
Refresh Forces the form to repaint (redraw) itself and any child
controls.
Select Select this form.
SendToBack Sends the form to the back of the stacking order.
SetBounds Sets the bounds of the form.
Show. Makes the form display by setting the visible property to true.
ShowDialog Displays the form as a modal dialog box.

Prepared By Prof. Hemanta Bhatt Page 3


SDJ International College, Palsana

Form Events:
Windows forms also support events, when you click a form, a click event occurs,
and when the form is closed, a closed event occurs. Following table lists down
various important events related to a form.

Event Description

Activated Occurs when the form is activated in code or by the user.

Click Occurs when the form is clicked.

Closed Occurs before the form is closed.

Closing Occurs when the form is closing.

DoubleClick Occurs when the form control is double-clicked.

DragDrop Occurs when a drag-and-drop operation is completed.

Enter Occurs when the form is entered.

GotFocus Occurs when the form control receives focus.

HelpButtonClicked Occurs when the Help button is clicked.

KeyDown Occurs when a key is pressed while the form has focus.

KeyPress Occurs when a key is pressed while the form has focus.

KeyUp Occurs when a key is released while the form has focus.

Load Occurs before a form is displayed for the first time.

LostFocus Occurs when the form loses focus.

Occurs when the mouse pointer is over the form and a mouse
MouseDown
button is pressed.

MouseEnter Occurs when the mouse pointer enters the form.

MouseHover Occurs when the mouse pointer rests on the form.

Prepared By Prof. Hemanta Bhatt Page 4


SDJ International College, Palsana

MouseLeave Occurs when the mouse pointer leaves the form.

MouseMove Occurs when the mouse pointer is moved over the form.

Occurs when the mouse pointer is over the form and a mouse
MouseUp
button is released.

Occurs when the mouse wheel moves while the control has
MouseWheel
focus.

Move Occurs when the form is moved.

Resize Occurs when the control is resized.

Scroll Occurs when the user or code scrolls through the client area.

Shown Occurs whenever the form is first displayed.

VisibleChanged Occurs when the Visible property value changes.

Working with common controls


Label
 It is used to display text on the form which user can not edit.
 However user can edit contents of the label control at run time using text
property.
 The Prefix for the Label is ―lbl‖.
Properties:

Property Description

BackColor It is used to get or set background color of the label.


Font It is used to set Font Face, Font Style, Font Size and Effects of the text
associated with Label Control.
ForeColor It is used to get or set Forecolor of the text associated with Label
Control.

Prepared By Prof. Hemanta Bhatt Page 5


SDJ International College, Palsana

Enabled It is used to specify whether label control is enabled or not at run time.
It has Boolean value. Default value is true.
Image It is used to specify an image that is displayed in Label Control.
ImageAlign It is used to get or set alignment of the image that is displayed in the
Label control.
Text It is used to get or set text associated with the Label control.
TextAlign It is used to get or set alignment of the text associated with the Label
control.
Visible It is used to specify whether label control is visible or not at run time.
It has Boolean value. Default value is true.

Methods:

Method Description
Show It is used to show label control at run time.
Hide It is used to hide label control at run time.

Events:

Event Description
Click It is the default event of Label Control. It fires each time
user clicks on Label Control.
DoubleClick It fires each time user double clicks on Label Control.
TextChanged It fires each a text associated with Label Control is changed.

Example: Program that accepts two numbers from user and performs addition,
subtraction, multiplication and division of two numbers using Label, Textbox
and Button Control.

Prepared By Prof. Hemanta Bhatt Page 6


SDJ International College, Palsana

Source Code:
Public Class Form1
Dim a As Integer
Dim b As Integer
Dim ans As Integer

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


System.EventArgs) Handles btnadd.Click
a = txtno1.Text
b = txtno2.Text
ans = a + b
lblans.Text = Val(ans)
End Sub

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


System.EventArgs) Handles btnsub.Click
a = txtno1.Text
b = txtno2.Text
ans = a - b
lblans.Text = Val(ans)
End Sub

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


System.EventArgs) Handles btnmul.Click
a = txtno1.Text
b = txtno2.Text
ans = a * b
lblans.Text = Val(ans)
End Sub

Prepared By Prof. Hemanta Bhatt Page 7


SDJ International College, Palsana

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


System.EventArgs) Handles btndiv.Click
a = txtno1.Text
b = txtno2.Text
ans = a / b
lblans.Text = Val(ans)
End Sub
End Class

Text Box:
 It is used to accept textual input from the user. The user can add strings,
numerical values and a combination of those, but Images and other
multimedia content are not supported.
 By default, it takes a single line of text, however, you can make it accept
multiple texts and even add scroll bars to it. The prefix of TextBox is ―txt‖.

Properties:

Property Description
Name Indicates the name used in code to indentify the object.
Ex. txtname, txtaddress
Text Gets or sets the current text in the TextBox.

PasswordChar Indicates the character as a password.We can enter *? Etc


character for
password
TextAlign It is used for setting text alignment such as Left,Right,Center
ScrollBars For adding scrollbars. This property has values
 None
 Horizontal
 Vertical
 Both
Multiline It is used to set the TextBox Control to allow multiple lines.
MaxLength It is used for specifying the maximum character number the
TextBox Control will accept.
Enabled It is used to specify whether textbox control is enabled or
not at run time. It has Boolean value. Default value is true.
Readonly Gets or sets a value indicating whether text in the text box is
read-only.
if set to true, you will be able to use the TextBox Control, if
set to false, you won't be able to use the TextBox Control.
WordWrap Indicates whether a multiline text box control automatically
wraps

Prepared By Prof. Hemanta Bhatt Page 8


SDJ International College, Palsana

words to the beginning of the next line when necessary.


TabIndex Gets or sets the tab order of the control within its container.

Methods:

Method Description
Clear Clears all text from the text box control.
Cut Moves the current selection in the text box to the Clipboard.
Copy Copies the current selection in the text box to the Clipboard.
Paste Replaces the current selection in the text box with the contents of
the Clipboard.
Undo Undoes the last edit operation in the text box.
Focus Sets focus to the TextBox.
ToString() Returns a string that represents the TextBox control.

Events:
Event Description
TextChanged It is the default event of TextBox Control. It fires each time
a text in the TextBox control is changed
GotFocus It fires each time a focus is set on TextBox
LostFocus It fires each time a focus is lost from TextBox

Button:
 Button is a widely used control in application. It is used to perform an
action.
 Whenever user clicks on a button the click event associated with the
button is fired and the action associated with the event is executed.
 The prefix for button control is ―btn‖.
 We can set accelerator key for the button. It is also known as mnemonics. It
is represented by underlined characters.
 For example set text property of the btnans(button) as &Ans. It will display
underline under the character A now we call btnans button’s event by ALT
+A.

Prepared By Prof. Hemanta Bhatt Page 9


SDJ International College, Palsana

Properties:

Property Description
Name Indicates the name used in code to indentify the object.
Ex. btnans,btnshow.
Text Gets or sets the current text in the Button.
TextAlign It is used for setting text alignment such as
Left,Right,Center
Enabled It is used to specify whether textbox control is enabled or
not at run
time. It has Boolean value. Default value is true.
TabIndex Gets or sets the tab order of the control within its
container.
BackColor It is used to get or set background color.
Font It is used to set Font Face, Font Style, Font Size and Effects
of the text.
Visible It is used to specify whether the control is visible or not at
run time. It
has Boolean value. Default value is true.
FlatStyle It is used to get or set appearance of the Button
Control when user moves mouse on it or click on it. It
has following 4 options:
System, Popup, Standard, Flat
Image It is used to specify an image that is displayed on it.
ImageAlign It is used to get or set alignment of the image that is
displayed on it. control.
TextImageRelation It is used to get or set position of text in relation with
image. It has following 5 options:
(1) Overlay
(2) ImageAboveText
(3) TextAboveImage
(4) ImageBeforeText
(5) TextBeforeImage
It is used when user wants to display both text and image
on Button Control.

Methods:
Method Description
Show It is used to show Button control at run time.
Hide It is used to hide Button control at run time

Prepared By Prof. Hemanta Bhatt Page 10


SDJ International College, Palsana

Focus It is used to set input focus on Button Control at run time


Events:

Events Description

BackColorChanged A BackColorChaged event is found in button control


when the Background property is changed.
Click A Click event is found in the button control when the
control is clicked.
ContextManuChanged It is found in button control when the value of the
ContextMenu property is changed.
ControlAdded A ControlAdded event is found in button control when a
new control is added to the Control.ControlCollection.
CursorChanged A CursorChanged event is found in button control when
the value of the control is changed.
DoubleClick When the user makes a double click on the button, a
double click event is found in the button control.
TextChanged It is found in the button control when the value of the text
property is changed.
DragDrop The DragDrop event is found in the button control when
the drag and drop operation is completed in the Form.

Example:

Prepared By Prof. Hemanta Bhatt Page 11


SDJ International College, Palsana

Source Code:
Public Class btn_ex
Dim a As String
Private Sub btndisplay_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btndisplay.Click
a = MessageBox.Show("Name: " & txtname.Text & vbCrLf & "Password:" &
txtpwd.Text & vbCrLf & "Address:" & txtadd.Text)
End Sub

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


System.EventArgs) Handles btnclr.Click
txtname.Text = ""
txtpwd.Text = ""
txtadd.Text = ""
txtname.Focus()
End Sub

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


System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
End Class

Checkbox:
 It is used to set true/false or yes/no type options. The user can select or
deselect it. When a check box is selected it has the value True, and when it is
deselected, it has the value False.
 The prefix of the checkbox is “chk”.

Properties:

Property Description
Text Gets or sets the current text of it.
Appearance It is used to determining the appearance of the check box.
Autocheck When check box is clicked it automatically change state
(True/False). By default
it is true.
CheckAlign It Determine the location of the checkbox inside the control. By
default it is
Middleleft.
Prepared By Prof. Hemanta Bhatt Page 12
SDJ International College, Palsana

Checked Indicating whether the check box is in checked state(True/False).


ThreeState Indicates whether check box will allow three check states rather
than two.
CheckState Indicates the state of the
checkbox. There are 3 types
of chechstate:
-checked
-unchecked
-indeterminate.

Events:
Event Descrption
CheckedChanged Raised when Checked property of the CheckBox control is
changed

Methods:

Methods Description
GetPreferredSize Retrieves the size of a rectangular area into which a control
can be fitted.
NotifyDefault Notifies the Button whether it is the default button so that it
can adjust its appearance accordingly.
Select Activates the control.
ToString Returns a String containing the name of the Component, if
any. This method should not be overridden.

Example:

Prepared By Prof. Hemanta Bhatt Page 13


SDJ International College, Palsana

Source Code:
Public Class chkfrm

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


System.EventArgs) Handles btnsubmit.Click
Dim str As String
str = " "
If chkfrd.Checked = True Then
Str &= chkfrd.Text
Str &= " "
End If

If chknp.Checked = True Then


str &= chknp.Text
str &= " "
End If
If ckhws.Checked = True Then
str &= ckhws.Text
str &= " "
End If
If chkothr.Checked = True Then
str &= TextBox1.Text
str &= " "
End If

If str <> Nothing Then


MsgBox(str + vbLf + "Thank you")
End If

End Sub

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


System.EventArgs) Handles btnshw.Click
If chksp.Checked = True Then
MsgBox("Sports checked", MsgBoxStyle.OkCancel)
Else
MsgBox("Sports unchecked", MsgBoxStyle.OkCancel)
End If
End Sub

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


System.EventArgs) Handles chkms.CheckedChanged
If chkms.Checked = True Then
MsgBox("Music checked")
Else
MsgBox("Music unchecked")
End If
End Sub
End Class

Prepared By Prof. Hemanta Bhatt Page 14


SDJ International College, Palsana

Radio Button:
 It is also known as an option button. We can check one radio button at a
time. Radio button are generally use for one in multiple options like
Gender, Stream etc. We can checked or unchecked the radiobutton.
 The prefix of the radiobutton is either “opt” or “rad”.

Properties:

Property Description
Text Gets or sets the current text of it.
TextAlign It is used for setting text alignment such as Left, Right, Center
Appearance It is used to determining the appearance of it (normal or button).
Enabled It is used to specify whether the control is enabled or not at run
time. It has Boolean value. Default value is true.
Visible It is used to specify whether the control is visible or not at run time. It
has Boolean value. Default value is true.
Autocheck When check box is clicked it automatically change state (True/False).
By default it is true.
CheckAlign It Determine the location of the checkbox inside the control. By
default it is Middleleft.
Checked Indicating whether the check box is in checked state (True/False).

Events:

Events Description
AppearanceChanged Occurs when the value of the Appearance property of the
RadioButton control is changed.
CheckedChanged Occurs when the value of the Checked property of the
RadioButton control is changed.

Methods:

Methods Description
Contains The Contains() method is used to check if the defined control
is available in the RadioButton control.
Focus The Focus() method is used to set the input focus to the
window form's RadioButton control.
GetAutoSizeMode It is used to return a value that represents how the control
will operate when the AutoSize property is enabled in the
RadioButton control of the Window form.
Update It is used to reroute an invalid field, which causes control in
Prepared By Prof. Hemanta Bhatt Page 15
SDJ International College, Palsana

the client region.


ResetText As the name suggests, a ResetText() method is used to reset
the property of text to its default value or empty.

Example:

Source Code:

Public Class Form1

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


System.EventArgs) Handles MyBase.Load
Me.Text = "Radio Buttton Demo"
End Sub

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


System.EventArgs) Handles rad_red.CheckedChanged
Me.BackColor = Color.Red
End Sub

Prepared By Prof. Hemanta Bhatt Page 16


SDJ International College, Palsana

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


System.EventArgs) Handles radgreen.CheckedChanged
Me.BackColor = Color.Green
End Sub

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


System.EventArgs) Handles radblue.CheckedChanged
Me.BackColor = Color.Blue
End Sub

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


System.EventArgs) Handles radblack.CheckedChanged
Me.ForeColor = Color.Black
End Sub

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


System.EventArgs) Handles radwhite.CheckedChanged
Me.ForeColor = Color.White
End Sub

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


System.EventArgs) Handles radred1.CheckedChanged
Me.ForeColor = Color.Red
End Sub
End Class

Date Time Picker:


It is used to select date and time.

Properties:

Property Description
BackgroundImage It is used to set background Image for the DateTimePicker.
CalendarFont It is used to set the font style for the calendar in the
DateTimePicker control.
CustomFormat It is used to set the custom date and time format string in
the
DateTimePicker control. dd/mm/yy
Checked It is used to check whether the value property is checked
with a valid date and time in the DateTimePicker control.

Prepared By Prof. Hemanta Bhatt Page 17


SDJ International College, Palsana

Format It is used to set the format for the Date and time displayed
in the Windows Form. dd/mm/yyyy
MaxDate It is used to set the maximum date value.
Name Indicates the name used in code to indentify the object.
MinDate It is used to set the minimum date value.
Value The current date and time value for this control.

Events:

Event Description
Click Occurs when the control is clicked.
CloseUp Occurs when the drop-down calendar is dismissed and
disappears.
DoubleClick Occurs when the control is double-clicked.
DragDrop Occurs when a drag-and-drop operation is completed.
ForeColorChanged Occurs when the value of the ForeColor property changes.
FormatChanged Occurs when the Format property value has changed.

Methods:
Method Description
Select It is used to start or activate the DateTimePicker control.
Show It is used to display the control.
ToString It is used to return string that represent date and time.

Example:

Prepared By Prof. Hemanta Bhatt Page 18


SDJ International College, Palsana

Source Code:

Public Class Form1


Dim a, b As DateTime
Dim c, d As TimeSpan
Private Sub btncal_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btncal.Click
a = DateTimePicker1.Value
b = Date.Now
c = b.Subtract(a)
Label3.Text = Convert.ToInt32(Val(c.TotalDays) / 365)
End Sub
End Class

List Box:
 It is used to display list of items. It allows user to select one or more
items from the listbox.
 We can add or design the list box by using the properties and events at
runtime.
 It is used for displaying larger number of choices.
 A scroll bar is automatically appears when many items in the ListBox.
By default we can select only one item from ListBox.
 The Prefix is “lst”.

Properties:

Property Description
Name It represents unique name of control. It is used in the coding.
DataSource It is used to bind a collection of items to a ListBox
DisplayMember It gets or sets the field to be displayed in the ListControl.
Items It gets the items of the ListBox
.
Multicolumn It allows multiple items to be displayed in the ListBox. It
has Boolean Value (True/False). By default it is false.
.

Prepared By Prof. Hemanta Bhatt Page 19


SDJ International College, Palsana

SelectionMode It defines how items are selected in the Listbox.The values


of selectionMode are given below:
- None: No item can be selected
- One: Only one item can be selected (by default)
- Multisimple: Multiple Item can be selected
- MultiExtended: Multiple Item can be selected and user
can use SHIFT,CTRL and arrow keys to make selections
SelectedIndex It returns the index of the selected item. If more than one
item is selected, it represents the lowest index. If no item is
selected then it returns -1.
SelectedIndices It returns the indices of all selected items. It is used when
more than one item is selected.
SelectedItem It returns the text of selected item. If more than one item is
selected,
then it returns the 1st Selected Item.
SelectedItems It returns the text of all selected items.
Sorted Set the ListBox item in sorted order either in ascending or
descending. It has Boolean value (True/False). By default
false.
ValueMember It is used to get or set the actual value for the items in the
control.

Events:

Event Description
Click It occurs when ListBox is selected
SelectedIndexChanged It occurs when SelectedIndex property is changed

Methods:

Method Description
ClearSelected Unselects all the items in the ListBox.
FindString It returns the index of specified string. If it does not match
then returns -1.
FindStringExact It returns the index of exactly matches of the specified string.
GetSelected It checks whether given index of item is selected or not. It
returns Boolean value. If item is selected then it returns true
otherwise false.
SetSelected It selects or deselects the item of the given index.

Prepared By Prof. Hemanta Bhatt Page 20


SDJ International College, Palsana

Eample:

Source Code:

Public Class Form1

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


System.EventArgs) Handles btnadd.Click
ListBox1.Items.Add(TextBox1.Text)
Label3.Text = ListBox1.Items.Count()
TextBox1.Text = ""
TextBox1.Focus()
End Sub

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


System.EventArgs) Handles btnremove.Click
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
Label3.Text = ListBox1.Items.Count()
End Sub

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


System.EventArgs) Handles btnclear.Click

Prepared By Prof. Hemanta Bhatt Page 21


SDJ International College, Palsana

ListBox1.Items.Clear()
Label3.Text = ListBox1.Items.Count()
End Sub
End Class
Combo Box:
 The ComboBox control is used to display a drop-down list of various items.
 It is a combination of a TextBox and ListBox.
 You can populate the list box items either from the properties window or at
runtime.
 User can select only one item from the given list.
 Combo Box has three different Drop Down style: Simple, drop down and
drop-down list
 The prefix of ComboBox is “cmb”.

Properties:

Property Description
DataBindings It gets the data binding for the control.
Name It represents unique name of control. It is used in the
coding.
DataSource It is used to bind a collection of items to a ComboBox
DisplayMember It gets or sets the field to be displayed in the
ComboBox.
ValueMember It is used to get or set the actual value for the items in
the control.
Items It gets the items of the ComboBox.
.
SelectedIndex It returns the index of the selected item. If more than
one item is selected, it represents the lowest index. If no
item is selected then it returns -1.
SelectedItem It returns the text of selected item. If more than one item
is selected, then it returns the 1st Selected Item.
SelectedText Gets or sets the text that is selected in the editable
portion of a ComboBox
SelectedValue Gets or sets the value of the member property specified
by the ValueMember property.
Sorted Gets or sets a value indicating whether the items in the
combo box are sorted.
IntegralHeight Indicates whether the combo box should resize to
avoid showing partial items.(true(Default)/false)

Prepared By Prof. Hemanta Bhatt Page 22


SDJ International College, Palsana

MaxDropDownItems The maximum number of entries to be display in the


drop down list.

Methods:
Method Description
SelectAll Selects all the text in the editable area of the combo box.
FindString It returns the index of specified string. If it does not match then
returns -1.
FindStringExact It returns the index of exactly matches of the specified string.

Events:
Event Description
SelectedIndexChanged It occurs when SelectedIndex property is changed

Example: Program to get the selected items in the combo box and show them in a
list box and sort the items.

Prepared By Prof. Hemanta Bhatt Page 23


SDJ International College, Palsana

Source Code:
Public Class cmb_box

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


System.EventArgs) Handles btnfill.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
' ComboBox1.Items.Add("Good Movies")
' ComboBox1.Items.Add("Good Books")
' ComboBox1.Items.Add("Education")
' ComboBox1.Items.Add("Road Trip")
ComboBox1.Items.Add("Health")
' ComboBox1.Items.Add("Food for all")
' ComboBox1.Items.Add("Shelter for all")
' ComboBox1.Items.Add("International Trip")
' ComboBox1.Items.Add("Peace")
' ComboBox1.Items.Add("Liberty")
' ComboBox1.Items.Add("Freedom of Speech")
ComboBox1.Text = "Select from..."
End Sub

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


System.EventArgs) Handles btnadd.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)
End If
End Sub

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


System.EventArgs) Handles btnsort.Click
ComboBox1.Sorted = True
End Sub

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


System.EventArgs) Handles btnclear.Click
ComboBox1.Items.Clear()
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal


e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Label3.Text = ComboBox1.SelectedItem.ToString()
End Sub
End Class

Prepared By Prof. Hemanta Bhatt Page 24


SDJ International College, Palsana

Picture Box:
 It is used for displaying images on the form. The Image property of the
control allows you to set an image both at design time and at run time.
Properties:

Property Description
Name It represents unique name of control. It is used in the
coding.
Image Gets or sets the image that is displayed in the control.
SizeMode Determines the size of the image to be displayed in the
control. This property takes its value from the
PictureBoxSizeMode enumeration, which has values −
 Normal − the upper left corner of the image is
placed at upper left part of the picture box
 StrechImage − allows stretching of the image
 AutoSize − allows resizing the picture box to
the size of the image
 CenterImage − allows centering the image in the
picture box
 Zoom − allows increasing or decreasing the
image size to maintain the size ratio.
Height Gets or sets the height of the image
Width Gets or sets the width of the image

Events:

Events Description
Click Occurs when the control is clicked.
FontChanged Occurs when the value of the Font property changes.
Enter Overrides the Control.Enter property.
ForeColorChanged Occurs when the value of the ForeColor property changes.

Methods:

Methods Description
Load Displays an image in the picture box
ToString Returns the string that represents the current picture box.

Prepared By Prof. Hemanta Bhatt Page 25


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1

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


System.EventArgs) Handles MyBase.Load
Me.Text = "Picture Box Exmaple"
Button1.Text = "Click to Display Image"
Button1.ForeColor = Color.Crimson
End Sub

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


System.EventArgs) Handles Button1.Click
PictureBox1.Image = Image.FromFile("D:\VS Projects\visual-basic-
net.jpg")
'PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
PictureBox1.Height = 250
PictureBox1.Width = 350
Button1.Visible = False
End Sub
End Class

Rich Text Box:


 It is a text editing control that allows users to enter and format text using a
variety of fonts, colors, and styles.
 It is an advance version of textbox. It can load RTF (Rich Text Format),
TXT format files for reading or editing. For example WordPad.

Prepared By Prof. Hemanta Bhatt Page 26


SDJ International College, Palsana

Properties:
Property Description
Text Gets or sets current text of the control.
SelectionAlignment Gets or sets the Alignment to apply to current selection
SelectionBackColor Gets or sets background color of text.
SelectionBullet Gets or sets bullet list
SelectionFont Gets or sets font of current selection
SelectionColor Gets or sets text color of the current text selection.
SelectedText Gets or sets the selected text
ZoomFactor Define the scaling factor of it.

Methods:
Method Description
AppendText Appends text to the end of the control's text.
Cut Cuts the selected text to the Clipboard.
Copy Copies the selected text to the Clipboard.
Paste Replaces the current selection in the text box with the
contents of the
Clipboard
Undo Undoes the last edit operation in the control.
Find Finds the specified text within the control.
LoadFile Loads the contents of a file into the control.
SaveFile Saves the contents of the control to a file.
Clear Clears all text from the control.

Events:
Events Description
Click Triggered when control is clicked.
LinkClick Triggered when user clicks on the link within the text.
Selectionchanged Triggered when selection property is changed.
VScroll Occurs when vertical scroll bars are clicked.

Prepared By Prof. Hemanta Bhatt Page 27


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1
Dim a, b As Integer
Dim str As String
Private Sub btndisplay_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles btndisplay.Click
a = Val(txtfirst.Text)
b = Val(txtsecond.Text)
For i = 1 To 10
For j = a To b
RichTextBox1.AppendText(String.Format(" {0} * {1} =
{2} ", j, i, (j * i).ToString().PadRight(10)))
Next
RichTextBox1.AppendText(vbCrLf)
Next
End Sub
End Class

Tree View:
 It is a powerful tool that allows you to display hierarchical data in a tree
structure. The control can be used to display a variety of data, including files
and folders, organizational charts, family trees, and more.

Prepared By Prof. Hemanta Bhatt Page 28


SDJ International College, Palsana

 It is collection of nodes. The main starting node is called root node. Under
the root, a real tree is made of branches and leaves. A node can have a node
as a child. We can expand and collapse these nodes by clicking them.
 Tree view has nodes collection.

Properties of Node Collection:


Property Description
Count It returns total number of elements.
Items It returns the nodes of the given index.

Methods:

Method Description
Add It adds nodes in the Tree view
Clear It clear all the nodes from the Tree view
Contains It checks whether the given node is a part of Tree view or not.
It returns Boolean value.
Insert We can insert node in the Tree View in any place by using this
method. It contains two arguments. Index and node.
Remove It removes the node from the Tree View. The argument of Remove ()
method is the node.
RemoveAt It removes the node from the Tree View by index.

Properties of Tree View:


Property Description
Nodes It is used to gather all the nodes used in the tree.
SelectedNode It is used to get or set the tree node that is selected in the
tree view control.
ShowRootLines It gets or sets a value that represents whether you want to
draw lines between the trees nodes connected with the root of
the tree view.
Path Separator The Path Separator property of the Tree View Control is used
to set a delimiter string between the tree node paths.
ShowPlusMinus It is used to get or set a value representing whether you want
to display the plus (+) or minus sign button next to tree nodes
containing the child nodes.
ShowLines It takes a value representing whether you want to draw lines
between the tree nodes of the tree view control.

Prepared By Prof. Hemanta Bhatt Page 29


SDJ International College, Palsana

TopNode It is used to get or set full visible tree nodes on top of other
nodes in the tree view control.
VisibleCount It is used to obtain the fully visible tree node in the tree view
control.
ItemHeight The ItemHeight property is used to set the height of each tree
node in control.
Scrollable The Scrollable property is used in the tree-view to display the
scroll bar by setting the value in control.

Methods:

Method Description
ExpandAll() As the name suggests, an ExpandAll method is used to
expand all the tree nodes.
CollapseAll It is used to collapse all tree nodes, including all child
nodes in the tree view control.
Sort() A Sort method is used to sort the tree nodes that are
available in the tree view control.
GetNodeCount It is used to count the number of nodes that are available in
the tree view control.
ToString ToString method is used to return the name of the string that
is in the tree view control.

Prepared By Prof. Hemanta Bhatt Page 30


SDJ International College, Palsana

Example:

Source Code:
Public Class frmtreeview
Sub filltreeview()
TreeView1.Nodes.Add("Database") 'this is root node
TreeView1.Nodes(0).Nodes.Add("sql server")
TreeView1.Nodes(0).Nodes.Add("my sql")
TreeView1.Nodes(0).Nodes.Add("Oracle")
TreeView1.Nodes.Add("Programming langauage") 'this is root node
TreeView1.Nodes(1).Nodes.Add("C#")
TreeView1.Nodes(1).Nodes.Add("VB")
TreeView1.Nodes(1).Nodes.Add("Java")
End Sub

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


As System.EventArgs) Handles btnselectednode.Click
MsgBox(TreeView1.SelectedNode.Text)
MsgBox(TreeView1.SelectedNode.FullPath)
End Sub

Prepared By Prof. Hemanta Bhatt Page 31


SDJ International College, Palsana

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


System.EventArgs) Handles btnchildnode.Click
MsgBox(TreeView1.SelectedNode.Nodes(0).Text)
MsgBox(TreeView1.SelectedNode.Nodes(1).Text)
MsgBox(TreeView1.SelectedNode.Nodes(2).Text)
End Sub

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


System.EventArgs) Handles MyBase.Load
filltreeview()
End Sub

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


System.EventArgs) Handles btncount.Click
MsgBox(TreeView1.Nodes.Count)
End Sub

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


System.EventArgs) Handles btnexpand.Click
TreeView1.ExpandAll()
Dim nodeCount As Integer = TreeView1.GetNodeCount(True)
MessageBox.Show("Total nodes in the TreeView control: " &
nodeCount.ToString())

End Sub

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


System.EventArgs) Handles btncollapse.Click
TreeView1.CollapseAll()
End Sub

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


System.EventArgs) Handles btnclr.Click
TreeView1.Nodes.Clear()
End Sub

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


System.EventArgs) Handles btnscroll.Click
TreeView1.Scrollable = True
End Sub
End Class

Tool Tip:
 A tooltip is a small pop-up window that displays some information when
you rollover on a control.
 Tooltip class represents a tooltip control. Once a Tooltip object is
created, we need to call SetToolTip method and pass a control and text.

Prepared By Prof. Hemanta Bhatt Page 32


SDJ International College, Palsana

Properties:

Property Description
Active A tooltip is currently active.
AutomaticDelay Automatic delay for the tooltip.
AutoPopDelay The period of time the ToolTip remains visible if the
pointer is stationary on a control with specified ToolTip
text.
InitialDelay Gets or sets the time that passes before the ToolTip
appears.
IsBaloon Gets or sets a value indicating whether the ToolTip
should use a balloon window.
ReshowDelay Gets or sets the length of time that must transpire before
subsequent ToolTip windows appear as the pointer moves
from one control to another.
ShowAlways Displays if tooltip is displayed even the parent control is
not active.
ToolTipIcon Icon of tooltip window.

ToolTipTitle Title of tooltip window.

UseAnimation Represents weather an animation effect should be used


when displaying the tooltip.
UseFading Represents weather a fade effect should be used when
displaying the tooltip.

Methods:

Events Description
GetToolTip Returns a tool tip text.
SetToolTip Connects tool tip text with the tool tip.

Prepared By Prof. Hemanta Bhatt Page 33


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1

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


System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(txtfname, "Enter Your first name")
ToolTip1.SetToolTip(txtlname, "Enter Your last name")
ToolTip1.SetToolTip(txtAge, "Enter Your age")
ToolTip1.SetToolTip(btnshow, "Show record")
End Sub

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


As System.EventArgs) Handles btnshow.Click
MessageBox.Show("First Name: " & txtfname.Text & vbCrLf &
"Last Name:" & txtlname.Text & vbCrLf & "Age" & txtage.Text)
End Sub
End Class

Prepared By Prof. Hemanta Bhatt Page 34


SDJ International College, Palsana

Progress Bar:
 It is used to graphically display the progress of particular task. Thus using
Progress Bar control you can display how much task has been completed
and how much task is remaining.
 It shows the progress of any background activity. It is a good idea to show
the progress to the end user when an application is performing complex or
time consuming background tasks.

Properties:
Property Description
Minimum It Get or Set Lower Bound of the range
within which ProgressBar Control works.
Maximum It Get or Set Upper Bound of the range within which
ProgressBar Control works.
Value It Get or Set current value of the ProgressBar within
range specified using Minimum and Maximum
property.
Step It Get or Set Step value by which the current value of
ProgressBar control is Increment.
Style It is used to set the Style of ProgressBar Control. It
can have one of the following value: Blocks,
Continuous, Marquee.
Visible It is used to set weather ProgressBar control is visible
on the form or not. It has boolean value true or false.
Default value is true.
Enabled It is used to set weather ProgressBar control is
enabled or not. It has boolean value true or false.
Default value is true.
MarqueeAnimationSpeed It Get or Set speed of marquee animation when Style
property of ProgressBar Control is set to marquee.
The speed is in milisecond. Default value is 100 ms.

Methods:

Methods Description
Increment It is used to increment the current value of ProgressBar
Control by specific value.
Syntax: ProgressBar1.Increment(value)
PerformStep It is used to increment the current value of ProgressBar
Control by the value specified in the Step property of

Prepared By Prof. Hemanta Bhatt Page 35


SDJ International College, Palsana

ProgressBar.
Syntax:progressBar1.PerformStep()

Example:

Source Code:
Public Class Form1
Dim a As Integer
Private Sub btnstart_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnstart.Click
Timer1.Enabled = True
ProgressBar1.Maximum = 100
'a = 1
End Sub

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


As System.EventArgs) Handles btnstop.Click
Timer1.Stop()
End Sub

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


As System.EventArgs) Handles btnclear.Click
Timer1.Stop()
ProgressBar1.Value = 0
Label1.Text = ""
End Sub

Prepared By Prof. Hemanta Bhatt Page 36


SDJ International College, Palsana

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


System.EventArgs) Handles Timer1.Tick
ProgressBar1.Value = ProgressBar1.Value + 1
Label1.Text = "Process " & a & " % Completed"
a += 1
If a > 100 Then
Timer1.Enabled = False
End If
End Sub

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


As System.EventArgs) Handles btnreset.Click
' a = 1
ProgressBar1.Value = 0
Label1.Text = ""
End Sub
End Class

Masked Text Box:


 The .Net Masked TextBox control provides a mechanism to validate user
input on a form.
 For example, if you need a Textbox that should accept number in a certain
format.
 It is similar to the textbox control. But it provides access to mask or change
the format of input as well as output.
 The mask is used to distinguish between proper and improper user input.

Properties:
Property Description
Mask It is used to get or set format string which determines
whether characters entered in MaskedTextBox are valid or not.
AllowPromptAsI It is used to specify whether Prompt character can be entered
nput as valid input character in MaskedTextBox or not. It has
Boolean value. Default value is true.
AsciiOnly It is used to specify whether only ASCII characters can be
entered as valid input character in MaskedTextBox or not. It
has Boolean value. Default value is false.
BeepOnError It is used to specify whether control will generate system
beep sound on each invalid character input or not. It has
Boolean value. Default value is false.
Prepared By Prof. Hemanta Bhatt Page 37
SDJ International College, Palsana

PromptChar It is used to get or set Prompt character for MaskedTextBox


Control. This character is displayed in MaskedTextBox when
user has not entered any character
Text It is used to get or set text associated with it.
TextAlign It is used to get or alignment of the text associated with it.
TabIndex It is used to get or set Tab order of it.
TabStop It is used to specify whether user can use TAB key to set
focus on it or not. It has Boolean value. Default value is true.
Visible It is used to specify whether the Control is visible or not at
run time. It has Boolean value. Default value is true.

Methods:
Method Purpose
Append Text It is used to append text at the end of current text in it.
Clear It is used to clear all text from it.
Cut It is used to move current selection of it into clipboard.
Copy It is used to copies selected text of it into clipboard.
Paste It is used to replace current selection of MaskedTextBox by
contents of clipboard. It is also used to move contents of
Clipboard to MaskedTextBox control where cursor is currently
located.
Select It is used to select specific text from it.
SelectAll It is used to select all text of it.
DeselectAll It is used to deselect all text selected in it.
Show It is used to show the control at run time.
Hide It is used to hide the control at run time.
Focus It is used to set input focus on the control at run time.

Events:
Event Description
MaskChanged It fires each time a mask property is changed.
TextChanged It fires each time a text in the MaskedTextBox control changed.

Prepared By Prof. Hemanta Bhatt Page 38


SDJ International College, Palsana

Example:

Notify Icon:
 It is used to add system tray notification functionality to a Windows Forms
application.
 When an application is run, an icon will be added to the system tray and we
can add double click or menus to the icon to take some actions.

Properties:
Property Description
Icon Set the icon for the NotifyIcon.
ContentMenuStrip The short cut menu to show when the user right clicks the
icon.
Text Get or set tool tip text when mouse hovers the icon.
Visible Used to make the icon visible or invisible.

Methods:

Methods Description
Dispose Releases all resources used by the Component.
GetType Gets the Type of the current instance.
Prepared By Prof. Hemanta Bhatt Page 39
SDJ International College, Palsana

GetService Returns an object that represents a service provided by


the Component or by its Container.
ToString Returns a String containing the name of the Component, if any.
This method should not be overridden.

Events:

Events Description
BalloonTipClicked Occurs when the balloon tip is clicked.
Click Occurs when the user clicks the icon in the notification area.
DoubleClick Occurs when the user double-clicks the icon in the
notification area of the taskbar.
MouseUp Occurs when the user releases the mouse button while the
pointer is over the icon in the notification area of the taskbar.
MouseDown Occurs when the user presses the mouse button while the
pointer is over the icon in the notification area of the taskbar.

Link Label:
 It is similar to Label control, but it can display a hyperlink.
 Multiple hyperlinks can be specified in the Text of the control.
 Each hyperlink can perform a different task within an application.

Properties:

Property Description
AutoSize Gets or sets a value indicating whether the control automatically
adjusts its size to fit its contents.
LinkArea Gets or sets the area of the control that is treated as a link.
LinkBehavior Gets or sets a value that specifies the behavior of the link.
Links Gets the collection of links in the control
LinkColor Gets or sets the color used for links in the control.
Text Gets or sets the text displayed by the control.

Methods:

Method Description
DoDragDrop Initiates a drag-and-drop operation.
Focus Sets input focus to the control.
OnLinkClicked Raises the LinkClicked event.
ToString Returns a string representation of the control.

Prepared By Prof. Hemanta Bhatt Page 40


SDJ International College, Palsana

Events:

Event Description
LinkClicked Triggered when the link is clicked.

Example:

Source Code:
Public Class linklabel

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


System.EventArgs) Handles Button1.Click
Process.Start("WWW.Google.com")
End Sub

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


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles
LinkLabel1.LinkClicked
Process.Start("WWW.Google.com")
End Sub

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


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles
LinkLabel2.LinkClicked
functions.Show()
End Sub

Prepared By Prof. Hemanta Bhatt Page 41


SDJ International College, Palsana

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


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles
LinkLabel3.LinkClicked
radiobtn.Show()
End Sub

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


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles
LinkLabel4.LinkClicked
Process.Start("WWW.Gmail.com")
End Sub
End Class

Checked List Box:


 It is a ListBox control with CheckBox displayed in the left side where user
can select a single or multiple items.

Properties:

Property Description
Items It gets or sets the items contained in the CheckedListBox
control.
CheckedItems It gets a collection of the checked items in the
CheckedListBox control.
CheckedIndices It gets a collection of the indices of the checked items in the
CheckedListBox control.
CheckOnClick It gets or sets a value indicating whether the checkboxes are
automatically checked or unchecked when the item is
clicked.
SelectionMode It gets or sets a value indicating whether the user can select
multiple items or only one item.
ThreeState It gets or sets a value indicating whether the checkboxes
have three states: checked, unchecked, and indeterminate.
DisplayMember It gets or sets the property to display for each item in the
CheckedListBox control.
ValueMember It gets or sets the property to use as the actual value of each
item in the CheckedListBox control.
DataSource It gets or sets the data source for the CheckedListBox
control.
ScrollAlwaysVisible It gets or sets a value indicating whether the vertical
scrollbar is always visible or not.

Method:
Method Description

Prepared By Prof. Hemanta Bhatt Page 42


SDJ International College, Palsana

SetItemChecked(index, It sets the check state of the item at the specified index
value) in the CheckedListBox control to the specified value.
GetItemChecked(index) It gets the check state of the item at the specified index
in the CheckedListBox control.
GetItemCheckState(inde It gets the check state of the item at the specified index
x) in the CheckedListBox control and returns it as
CheckState enumeration value.
SetItemCheckState(index It sets the check state of the item at the specified
, state) index in the CheckedListBox control to the specified
CheckState enumeration value.
GetItemText(index) It gets the text of the item at the specified index in the
CheckedListBox control.
FindStringExact(value) It searches for the item with the specified text and
returns the index of the first item found.
FindStringExact( It searches for the item with the specified text,
value, startIndex) starting from the specified index, and returns the
index of the first item

Events:
Event Description
SelectedIndexChanged It occurs when SelectedIndex property is changed

Example:

Prepared By Prof. Hemanta Bhatt Page 43


SDJ International College, Palsana

Source Code:
Public Class Form1

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


System.EventArgs) Handles btnadd.Click
CheckedListBox1.Items.Add(TextBox1.Text)
Label3.Text = CheckedListBox1.Items.Count
TextBox1.Text = ""
End Sub

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


As System.EventArgs) Handles btnremove.Click

Dim a = (From i In CheckedListBox1.CheckedItems).ToList


For Each i In a
CheckedListBox1.Items.Remove(i.ToString)
Next
Label3.Text = CheckedListBox1.Items.Count

End Sub

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


As System.EventArgs) Handles btnclear.Click
CheckedListBox1.Items.Clear()
Label3.Text = CheckedListBox1.Items.Count()

End Sub
End Class

3.1.2 Container Controls


It is a control that can contain other controls within it. They are used to organize
and group related controls, and to provide layout and positioning of controls within
a form or other container.

Prepared By Prof. Hemanta Bhatt Page 44


SDJ International College, Palsana

1. Group Box:
 A GroupBox control is a container control that is used to place Windows
Form child controls in a group.
 The purpose of GroupBox control is to define user interfaces where we can
categories related control in a group.

Property:
Text: It is used to specify the caption of the displayed GroupBox control.

Event:
Enter: Occurs when the mouse is entered.

Methods:
OnEnter: It raises Enter event.

2. Panel:
 It is used to group collections of controls.
 By default, the panel control is displayed without borders.
 Have the capacity to scroll by setting its AutoScroll property to True.

Property:

Property Description
Enabled It gets or set a value indicating whether the control can

Prepared By Prof. Hemanta Bhatt Page 45


SDJ International College, Palsana

respond to user interaction.


BorderStyle It indicates the border style for the control.
HScroll It gets or sets a value indicating whether the horizontal scroll
bar is visible.
VScroll It gets or sets a value indicating whether the vertical scroll bar
is visible.

Methods:

Methods Description
AdjustFromScrollbars It adjusts the scroll bars on the container based on the
current control positions and currently selected control.
GetScrollState It determines whether the specified flag has been set.
SetScrollState It sets the specified scroll state flag.
SetAutoScrollMargin It sets the size of the auto-scroll margins.

Event:
Paint()

3. TabControl:
 It contains tab pages which are represented by TabPage objects.
 The order of Tab pages in this collection reflects the order of the tabs appear
in the control.
 The user can change the currents TabPage by clicking one of the tabs in the
control.
 It manages a related set of tab pages.

Prepared By Prof. Hemanta Bhatt Page 46


SDJ International College, Palsana

Properties:
Property Description
Alignment It gets or sets area of control where the tabs are aligned.
Appearance It gets or sets visual appearance of the selected tab of control.
ImageList It gets or sets images to display on the tabs.
ImageSize It gets or sets image size of the tabs.
MultiLine It gets or sets indicating whether more than on row of tabs can
be displayed.
TabPages It gets the collection of tab pages in tab control.
TabCount It gets the number of tab pages in tab control.

Methods:
Methods Description
DeselectTab It deselects the tab control.
RemoveAll It removes all the tab pages and additional controls from this
tab control.
SelectTab It makes the tab with the specified index as current tab.

4. SplitContainer:
 It represents a control consisting of a movable bar that divides a display area
of a container into two resizable panels.
 You can add controls to the two resizable panels, and you can add other
SplitContainer controls to existing Splitcontainer panels to create many
resizable display areas.
 When the user passes the mouse pointer over splitter, the cursor changes,
which indicates that the controls inside the SplitContainer control can be
resized.

Exmaple:

Prepared By Prof. Hemanta Bhatt Page 47


SDJ International College, Palsana

5. FlowLayout Panel:
 It represents a panel that dynamically lays out its contents horizontally or
vertically.
 It contents can be wrapped from one row to the next or from one column to
the next.
 Alternatively, its contents can be clipped instead of wrapped.

6. TableLayout Panel:
 It representes a panel that dynamically lays out its contents in a grid
composed of and columns.
 Margin, DefaultPadding, Padding properties of TableLayout panel is similar
to FlowLayout panel.

3.1.4 Component Controls:

1. ImageList:
 It is a simple control that stores images used by other controls at runtime.

Properties:
Property Description
Images Gets the collection of images in the image list.
Prepared By Prof. Hemanta Bhatt Page 48
SDJ International College, Palsana

ColorDepth Gets or sets the color depth of the images in the image
list.
TransparentColor Gets or sets the color that is treated as transparent.
ImageSize Gets or sets the size of the images in the image list.
Tag Gets or sets an object that contains data about the control.

Methods:
Method Description
Clear Removes all the images from the image list.
Add Adds a new image to the image list, using the specified key to
identify it.
IndexOfKey Returns the index of the image with the specified key.
RemoveByKey Removes the image with the specified key from the image list.
Disposed Occurs when the control is disposed of by a call to the Dispose
method.
ItemAdded Occurs when an item is added to the image list.
ItemRemoved: Occurs when an item is removed from the image list.

Prepared By Prof. Hemanta Bhatt Page 49


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1
Dim n As Integer = 0

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


System.EventArgs) Handles Timer1.Tick
PictureBox1.Image = ImageList1.Images(n)
If (n = ImageList1.Images.Count - 1) Then
n = 0
Else
n += 1
End If
End Sub

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


System.EventArgs) Handles btnstart.Click
Timer1.Start()
End Sub

Prepared By Prof. Hemanta Bhatt Page 50


SDJ International College, Palsana

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


System.EventArgs) Handles btnstop.Click
Timer1.Stop()
End Sub
End Class

2. ErrorProvider:
 ErrorProvider allows us to set an error message for any control on the form
when the input is not valid.
 When an error message is set, an icon indicating the error will appear next to
the control and the error message is displayed as Tool Tip when the mouse
is over the control.

Properties:

Property Description
Name It is used to specify name of ErrorProvider Control.
BlinkRate It is used to specify rate in milisecond at which error icon
blinks.
BlinkStyle It is used to specify Blink Style for Error Icon. It can be:
AlwaysBlink, NeverBlink, BlinkIfDifferentError
Icon It is used to specify ICON to be displayed near to the control
when error is set for that control.

Methods:

Method Description
SetError It is used to set error message for particular control.
Ex:ErrorProvider1.SetError(ControlName,"ErrorMessage")
GetError It is used to retrieve current error message of particular control.
Ex: ErrorProvider1.GetError (ControlName).
Clear It is used to clear all the settings of ErrorProvider Control.
Ex:ErrorProvider1.Clear()

Prepared By Prof. Hemanta Bhatt Page 51


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1
Private Sub btnchk_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnchk.Click
If Not IsNumeric(TextBox1.Text) Or Not TextBox1.Text.Length = 10 Then
ErrorProvider1.SetError(TextBox1, "Please Enter Only 10 Digit
Number")
Else
ErrorProvider1.SetError(TextBox1, "")
MsgBox(TextBox1.Text)
End If
End Sub
End Class

3. HelpProvider:
 This control provides pop-up or online help for controls.
 HelpProvider control provides help with your application is very useful as it
allows users to understand it more easily.

Properties:

Property Description
HelpNamspace Gets or sets a value specifying the name of the Help file
associated with this HelpProvider.

Prepared By Prof. Hemanta Bhatt Page 52


SDJ International College, Palsana

Methods:

Methods Description
SetShowHelp It specifies whether Help is displayed for the specified
control.
SetHelpString It specifies the Help string associated with the specified
control.
SetHelpNavigator It specifies the Help command to use when retrieving
Help from the Help file for the specified control.
SetHelpKeyword It specifies the keyword used to retrieve Help when the
user invokes Help for the specified control.

4. Timer:
 It is used when user wants to perform some task or action continuously at
regular interval of time.

Properties:
Property Description
Name It is used to specify name of the Timer Control.
Enabled It is used to determine whether Timer Control will be enable
or not. It has Boolean value true or false. Default value is
false.
Interval It is used to specify interval in millisecond. Tick event of
Timer Control generates after the time which is specified in
Interval Property.
Methods:
Methods Description
Start This method is used to start the Timer Control.
Stop This method is used to stop the Timer Control.

Events:
Events Description
Tick Tick event of the Timer Control fires continuously after the
time which is specified in the Interval property of Timer
Control.

Example: Program to display traffic Signal using timer.

Prepared By Prof. Hemanta Bhatt Page 53


SDJ International College, Palsana

Source Code:
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
If OvalShape1.Visible Then
OvalShape1.Visible = False
OvalShape2.Visible = True
OvalShape3.Visible = False
ElseIf OvalShape2.Visible Then
OvalShape1.Visible = False
OvalShape2.Visible = False
OvalShape3.Visible = True
ElseIf OvalShape3.Visible Then
OvalShape1.Visible = True
OvalShape2.Visible = False
OvalShape3.Visible = False
End If
End Sub

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


System.EventArgs) Handles MyBase.Load
OvalShape1.Visible = True
OvalShape2.Visible = False

Prepared By Prof. Hemanta Bhatt Page 54


SDJ International College, Palsana

OvalShape3.Visible = False
End Sub
End Class

3.2 Working with Menus and Dialog Boxes

Menus and Tool Bars:


 A menu control allows hierarchal organization of elements associated
with commands and event handlers. In a typical Microsoft Windows
application, a menu bar contains several menu buttons (such as File, Edit,
and Window), and each menu button displays a menu.
 A menu contains a collection of menu items (such as New, Open, and
Close), which can be expanded to display additional menu items or to
perform a specific action when clicked.

MenuStrip:
 The MenuStrip control represents the container for the menu structure.

Let us add menu and sub-menu items. Perform the following steps:
 Drag and drop or double click on a MenuStrip control, to add it to the form.
 Click the Type Here text to open a text box and enter the names of the
menu items or sub-menu items you want. When you add a sub-menu,
another text box with 'Type Here' text opens below it.
 Complete the menu structure shown in the diagram above.
 Add a sub menu Exit under the File menu.

Prepared By Prof. Hemanta Bhatt Page 55


SDJ International College, Palsana

Properties:

Property Description
CanOverflow The CanOverflow property is used to authenticate
whether the control supports overflow functionality by
setting values in the MenuStrip control.
Stretch The Stretch property is used to obtain a value that
specifies whether the menustrip stretches from end to end
in the MenuStrip control.
GripStyle The GripStyle property obtains or sets the visibility of the
grip that uses the reposition of the menu strip control.
ShowItemToolTips It is used to obtain or set the value that determines if the
ToolTips are displayed for the MenuStrip Control.
DefaultSize The DefaultSize property is used to get the default
horizontal and vertical dimension of the MenuStrip in
pixel when it is first created.

Prepared By Prof. Hemanta Bhatt Page 56


SDJ International College, Palsana

Methods:
Methods Description
CreateAccessibilityInstance() It is used to create a new accessibility instance for
the MenuStrip Control.
ProcessCmdKey() The ProcessCmdKey method is used to process
the command key in the MenuStrip Control.
CreateDefaultItem() The CreateDefaultItem method is used to create a
ToolStripMenuItem with the specified text,
image, and event handlers for the new MenuStrip.
OnMenuActivate() It is used to initiate the MenuActivate event in the
MenuStrip control.
OnMenuDeactivate() It is used to start the MenuDeactivate event in the
MenuStrip control.

Events:

Events Description
MenuActivate When a user uses a menu bar control with a mouse or
keyboard, a MenuActivate event occurs.
MenuDeactivate The MenuDeactivate event occurs when the MenuStrip control
is deactivated in the Windows form.

ContextMenuStrip:
 Menu items which are available when you right click are called Context
Menus.
Steps of Context Menu:
 Drag and drop context menu strip control to the textbox control.
 When you do, you will notice two things. At the top of your form, you will
see this. And type cut copy and paste options. Then set the
ContextMenuStrip Property of the object.
 At the bottom of the page set the ContextMenuStrip property of the object.

Prepared By Prof. Hemanta Bhatt Page 57


SDJ International College, Palsana

Properties:

Properties Description
SourceControl Gets the last control that displayed the ContextMenuStrip
control.
AllowTransparency It gets or sets value indicating whether the opacity of the
form can be adjusted.
Opacity It determines the opacity of the form.
OwnerItem It gets or sets the Item that is owner of this DropDown.
TopMost It gets or sets a value indicating whether the form should be
displayed as a topmost form.

Methods:

Methods Description
Close It closes the control.
Show It displays the control on its default position.

ToolStrip:
 It provides a container for Windows toolbar objects.
 ToolStrip is the base class for MenuStrip, ContextMenuStrip and
StatusStrip.
 It can contain Button, Seperator, Label, DropDownButton, SplitButton,
TextBox and ComboBox.

Prepared By Prof. Hemanta Bhatt Page 58


SDJ International College, Palsana

StatusStrip:
 It represents a windows status bar.
 It can contain Status Label, DropDownButton, SplitButton and ProgressBar.
 It displays information about an object being viewed on a Form, or
information that relates to that operation of the object within your
application.

ToolStrip Container:
 It provides panels on each side of the form and a central panel that can hold
one or more control.
 It similar to SplitContainer.
 It uses four docked side panels one central panel to create a typical
arrangement.

Dialog Boxes:
 VB.Net contains built-in dialog boxes which allow user to create our own
Open, Save, Font and Color dialogs control that are similar to other
windows applications.
 The common dialog controls are as follows:
1. OpenFileDialog
2. SaveFileDialog
3. FontDialog
4. ColorDialog
5. PrintDialog
6. PrintPriviewDialog
7. PageSetupDialog
8. FolderBrowserDialog

Prepared By Prof. Hemanta Bhatt Page 59


SDJ International College, Palsana

1. OpenFileDialog:
 The OpenFileDialog control prompts the user to open a file and allows the
user to select a file to open.
 The user can check if the file exists and then open it.
 The OpneFileDialog conrtol class inherits from the abstract class
FileDialog.

Properties:

Properties Description
AddExtension Gets or sets a value indicating whether the dialog box
automatically adds an extension to a file name if the user omits
the extension.
CheckFileExists Gets or sets a value indicating whether the dialog box displays
a warning if the user specifies a file name that does not exist.
DefaultExt Gets or sets the default file name extension.
Prepared By Prof. Hemanta Bhatt Page 60
SDJ International College, Palsana

CustomPlaces Gets the custom places collection for this FileDialog instance.
FileName Gets or sets a string containing the file name selected in the
file dialog box.
FileNames Gets the file names of all selected files in the dialog box.
Filter Gets or sets the current file name filter string, which
determines the choices that appear in the "Save as file type" or
"Files of type" box in the dialog box.
Title Gets or sets the file dialog box title.

Methods:

Methods Description
OpenFile Opens the file selected by the user, with read-only permission.
The file is specified by the FileName property.
Reset Resets all options to their default value.

2. SaveFileDialog:
 The SaveFileDialog control prompts the user to select a location for saving a
file and allows the user to specify the name of the file to save data.
 The SaveFileDialog control class inherits from the abstract class FileDialog.

Prepared By Prof. Hemanta Bhatt Page 61


SDJ International College, Palsana

Properties and methods of SaveDialog are same as OpenFileDialog.

3. FontDialog:
 It prompts the user to choose a font from among those installed on the local
computer and lets the user select the font, font size, and color.
 It returns the Font and Color objects.

Properties:

Property Description
AllowVectorFonts Gets or sets a value indicating whether the dialog box
allows vector font selections.
AllowSimulations Gets or sets a value indicating whether the dialog box
allows graphics device interface (GDI) font simulations.
Color Gets or sets the selected font color.
AllowVerticalFonts Gets or sets a value indicating whether the dialog box
displays both vertical and horizontal fonts, or only
horizontal fonts.
Font Gets or sets the selected font.
FontMustExist Gets or sets a value indicating whether the dialog box
specifies an error condition if the user attempts to select a
font or style that does not exist.

Prepared By Prof. Hemanta Bhatt Page 62


SDJ International College, Palsana

MaxSize Gets or sets the maximum point size a user can select.
MinSize Gets or sets the minimum point size a user can select.

Methods:

Method Description
Reset Resets all options to their default values.
RunDialog When overridden in a derived class, specifies a common dialog
box.
ShowDialog Runs a common dialog box with a default owner.

Event:
Event Description
Apply Occurs when the Apply button on the font dialog box is clicked.

4. ColorDialog:
 The ColorDialog control class represents a common dialog box that displays
available colors along with controls that enable the user to define custom
colors.
 It lets the user select a color.

Prepared By Prof. Hemanta Bhatt Page 63


SDJ International College, Palsana

Properties:

Property Desscription
AllowFullOpen Gets or sets a value indicating whether the user can use the
dialog box to define custom colors.
AnyColor Gets or sets a value indicating whether the dialog box displays
all available colors in the set of basic colors.
CanRaiseEvents Gets a value indicating whether the component can raise an
event.
Color Gets or sets the color selected by the user.
CustomColors Gets or sets the set of custom colors shown in the dialog box.
FullOpen Gets or sets a value indicating whether the controls used to
create custom colors are visible when the dialog box is opened.
SolidColorOnly Gets or sets a value indicating whether the dialog box will
restrict users to selecting solid colors only.

Methods:

Method Description
Reset Resets all options to their default values, the last selected color
to black, and the custom colors to their default values.
RunDialog When overridden in a derived class, specifies a common dialog
box.
ShowDialog Runs a common dialog box with a default owner.

Events:

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

5. PrintDialog:
 The PrintDialog control lets the user to print documents by selecting a
printer and choosing which sections of the document to print from a
Windows Forms application.

Prepared By Prof. Hemanta Bhatt Page 64


SDJ International College, Palsana

There are various other controls related to printing of documents. Let us have a
brief look at these controls and their purpose. These other controls are:

 The PrintDocument control − it provides support for actual events and


operations of printing in Visual Basic and sets the properties for printing.
 The PrinterSettings control − it is used to configure how a document is
printed by specifying the printer.
 The PageSetUpDialog control − it allows the user to specify page-related
print settings including page orientation, paper size and margin size.
 The PrintPreviewControl control − it represents the raw preview part of
print previewing from a Windows Forms application, without any dialog
boxes or buttons.
 The PrintPreviewDialog control − it represents a dialog box form that
contains a PrintPreviewControl for printing from a Windows Forms
application.

Prepared By Prof. Hemanta Bhatt Page 65


SDJ International College, Palsana

Properties:
Property Description
AllowCurrentPage Gets or sets a value indicating whether the Current
Page option button is displayed.
AllowPrintToFile Gets or sets a value indicating whether the Print to
file check box is enabled.
AllowSelection Gets or sets a value indicating whether
the Selection option button is enabled.
AllowSomePages Gets or sets a value indicating whether the Pages option
button is enabled.
Document Gets or sets a value indicating the PrintDocument used to
obtain PrinterSettings.
PrinterSettings Gets or sets the printer settings the dialog box modifies.
PrintToFile Gets or sets a value indicating whether the Print to
file check box is selected.

Methods:

Method Description
Reset Resets all options to their default values.
RunDialog When overridden in a derived class, specifies a common dialog
box.
ShowDialog Runs a common dialog box with a default owner.

Prepared By Prof. Hemanta Bhatt Page 66


SDJ International College, Palsana

Example:

Source Code:
Public Class Form1

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


As System.EventArgs) Handles btncolor.Click
ColorDialog1.ShowDialog()
End Sub

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


As System.EventArgs) Handles btnfont.Click
FontDialog1.ShowDialog()
End Sub

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


As System.EventArgs) Handles btnopen.Click
OpenFileDialog1.ShowDialog()
End Sub

Prepared By Prof. Hemanta Bhatt Page 67


SDJ International College, Palsana

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


As System.EventArgs) Handles btnsave.Click
SaveFileDialog1.ShowDialog()
End Sub

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


As System.EventArgs) Handles btnprint.Click
PrintDialog1.ShowDialog()
End Sub
End Class

How to create Create an MDI form?


 Create a new VB.Net project, and then you will get a default form
Form1 then open the Properties window, set the following
properties
IsMdiContainer= true.
Name=frmMDI
Text=MDI form Text(for example Employee Management System)
WindowState=Maximized
 Then add two more forms in the project (Form2 , Form 3)
 Create a Menu on your form (Form1) and call these two forms on menu
click event.
 Then write down the following code on menu click event
Dim frm2 As New
frm2.MdiParent = Me
frm2.Show ()
 Then run your MDI form.

3.3 Exception Handling

Error:
Error means bug which means when you compile or run a program, abnormal
situation may raise, it is known as error.
There are different types of errors:
1. Syntax Error: The error raised by misspelled keywords or variable is called
syntax error. Compiler will normally catch these errors while you are coding
or after compilation of the program.
2. Logical Error: Due to mistake present in sequence of statement, code does
not act as expected. This type of error is called logical error.

Prepared By Prof. Hemanta Bhatt Page 68


SDJ International College, Palsana

3. Runtime error: The error which occurs when the code is executing is
called runtime error.

Exception Handling:
 Exception Handling is an in-built mechanism in .Net framework to detect
and handle run time error.
 The .Net framework contains lots of standard exception. The exceptions are
something different that occur during the execution of a program. They can
be because of user, logic or system errors.
 If a programmer do not provide a mechanism to handle these errors the
program’s execution is terminates.
 All the exceptions are directly or indirectly inherited from the Exception
class.

There are 2 types of exception handling:


1. Structured exception handling
2. Unstructured exception handling

1. Structured exception handling:


 It is implemented with Try…Catch…Finally statement, which is divided into
Try block, optional Catch blocks and an optional Finally block.
 The Try block contains code where exceptions can occur; the Catch block
contains code to handle the exception that occurs.
 If an exception occurs in Try block the code throws the exception, so it can
be caught and handled by the appropriate Catch statement.
 After the rest of the statement finishes, execution is always passed to the
Finally block.

Prepared By Prof. Hemanta Bhatt Page 69


SDJ International College, Palsana

Syntax:

Try
[ tryStatements ]
[ Exit Try ]

[ Catch [ exception [ As type ] ] [ When expression ]


[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]

[ Finally
[ finallyStatements ] ]
End Try

Try: It is used to identify the code block for which a specific exception will be
activated. It is follow by one or more catch blocks.
Catch: Catching of the Exception is done in this block. It is an exception
handler in which the Exception is handled.

Finally: It is used to run a set of statements whether an exception has occurred


or not. It is optional.

Exit Try: It is optional keyword that breaks out of the Try…Catch…Finally


structure.

The following table provides some of the predefined exception classes derived
from the Sytem.SystemException class –

Exception Class Description


System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers
to an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is
mismatched with the array type.

Prepared By Prof. Hemanta Bhatt Page 70


SDJ International College, Palsana

System.NullReferenceException Handles errors generated from de-referencing a


null object.
System.DivideByZeroException Handles errors generated from dividing a
dividend with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free
memory.
System.StackOverflowException Handles errors generated from stack overflow.

Example:

Source Code:
Public Class Form1

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


As System.EventArgs) Handles Button1.Click

Try
Dim no1, no2 As Integer, ans As Integer
no1 = TextBox1.Text
no2 = TextBox2.Text

ans = no1 + no2


MsgBox(ans, MsgBoxStyle.Information, "Addition")

Catch ex As Exception

Prepared By Prof. Hemanta Bhatt Page 71


SDJ International College, Palsana

MsgBox(ex.ToString, MsgBoxStyle.Critical, "Error")

Finally
MsgBox("Hello from Finally", MsgBoxStyle.Information,
"Addition")

End Try
End Sub
End Class

2. Unstructured Error Handling:


 It is simple to use.
 It is implemented with On Error GoTo statements. The syntax is as follow:

On Error {GoTo [line | 0 | -1] | Resume Next}

GoTo line | Label—Calls the error-handling code that starts at the line
specified at line. Here, line is a line label or a line number. If a runtime error
occurs, program execution goes to the given location. GoTo 0—Disables the
enabled error handler in the current procedure and reset it to nothing. It clears
the error object.

GoTo -1—Same as GoTo 0.

Resume Next—specifies that when an exception occurs, execution skips over


the statement that caused the problem and goes to the statement immediately
following and Execution continues from that point.

Example:
On Error Go to Label:

Dim n, m, ans As Integer

On Error GoTo Help


n = TextBox1.Text
m = TextBox2.Text
ans = n / m
MsgBox("Ans= " & ans)

Help:

Prepared By Prof. Hemanta Bhatt Page 72


SDJ International College, Palsana

MsgBox("Some Error", MsgBoxStyle.Critical, "Error")

On Error GoTo 0:
Dim n, m, ans As Integer

On Error GoTo Help


n = TextBox1.Text
m = TextBox2.Text
ans = n / m
MsgBox("Ans= " & ans)

Help:
On Error GoTo 0
MsgBox("Program completed")

On Error Resume Next:


Dim n, m, ans As Integer

On Error Resume Next


n = TextBox1.Text
m = TextBox2.Text
ans = n / m
MsgBox("Ans= " & ans)

Prepared By Prof. Hemanta Bhatt Page 73

You might also like