0% found this document useful (0 votes)
38 views40 pages

Unit Iv

The document discusses opening, closing, and hiding forms in Visual Basic .NET. It explains that to display different forms, code must be used to open and close them. It provides the code needed to open a form by creating an object of the form's type, showing the form, and setting the object to nothing to free up memory. The code to hide a form uses the Hide method, and to close it uses the Close method. The document also discusses form properties like BackColor and Text, and methods like Activate and Close.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views40 pages

Unit Iv

The document discusses opening, closing, and hiding forms in Visual Basic .NET. It explains that to display different forms, code must be used to open and close them. It provides the code needed to open a form by creating an object of the form's type, showing the form, and setting the object to nothing to free up memory. The code to hide a form uses the Hide method, and to close it uses the Close method. The document also discusses form properties like BackColor and Text, and methods like Activate and Close.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit-IV

Opening, Closing, and Hiding Forms with Visual Basic .NET


Having multiple forms as part of your Visual Basic .NET program may be
nice, but when your Visual Basic .NET program runs, it normally displays one
form. To make the other forms of your program appear (or disappear), you have to
use BASIC code to tell your program, “Okay, now put this particular form on the
screen and hide this other form out of sight.”
Opening a form
Before you can open (or close) a form, you need to know the specific name
of the form you want to open or close. The Solution Explorer window lists the
names of all the forms that make up your Visual Basic .NET program, such as a
form named frmMain.vb.
After you know the name of the form that you want to display, you need to use
BASIC command to open the form, such as the following:
Dim oForm As FormName
oForm = New FormName()
oForm.Show()
oForm = Nothing
In case the above four lines of BASIC code look confusing, here’s a quick
explanation on what they do:
1. The first line tells Visual Basic .NET, “Define an object named oForm, which
will represent the form that you want to open, which is called FormName.” So, if
you wanted to open a form named frmMain, you would type: Dim oForm As
frmMain (The oForm name is arbitrary and can be any name you choose. The “o”
is just shorthand for saying this is an object.)
2. The second line tells Visual Basic .NET, “Create a new object named oForm,
which represents the form represented by the name FormName.” (The main
difference between the first and second lines is that the first line just told Visual
Basic .NET to get ready to create an object to represent your form while the second
line actually creates that object to represent your form.)
3. The third line tells Visual Basic .NET, “Show the form represented by the
object oForm.”
4. The fourth line tells Visual Basic .NET, “Set the object named oForm to
nothing to free up the memory that it was taking up.”
It’s important to set the object to Nothing to free up memory because if you open
up too many forms without releasing the memory they use, the computer could run
out of memory and cause your program to freeze or crash.
VB.Net By Prof.A.D.Chavan Page 1
Unit-IV

Hiding (and showing) a form


If you want to temporarily make a form disappear, you can use the magic Hide
command, such as:
FormName.Hide()
After you’ve hidden a form, you’ll eventually want to make it visible again by
using the Show command, such as:
FormName.Show()
Closing a form
Hiding a form just tucks it out of sight, but the form is still loaded in the
computer’s memory. To clear a form out of memory, you need to use the Close
command, such as:
FormName.Close()
To make your program end, you have to shut down all your forms. At least
one form of your program needs to have an exit command such as an Exit button
or a File –> Exit command available from a pull-down menu. The BASIC code to
close the last form of your program looks like this:
Me.Close()
If you look at the BASIC code that Visual Basic .NET automatically creates for
each form, you’ll see a command that looks like this:
Form1 = Me
This command just tells Visual Basic .NET, “The word Me represents the current
form. So instead of having to type the form’s complete name, such as
frmMainWindow, you can just type Me instead.”
Basic Control
An object is a type of user interface element you create on a Visual Basic
form by using a toolbox control. In fact, in Visual Basic, the form itself is an
object. Every Visual Basic control consists of three important elements:
Control Properties
Properties which describe the object All the Visual Basic Objects can be
moved, resized, or customized by setting their properties. A property is a value or
characteristic held by a Visual Basic object, such as Caption or Fore
Color.Properties can be set at design time by using the Properties window or at run
time by using statements in the program code.
Object. Property = Value
Where, Object is the name of the object you're customizing.Property is the
characteristic you want to change.Value is the new property setting.
VB.Net By Prof.A.D.Chavan Page 2
Unit-IV

For example,
Form1.Caption = "Hello"
You can set any of the form properties using Properties Window. Most of
the properties can be set or read during application execution. You can refer to
Microsoft documentation for a complete list of properties associated with different
controls and restrictions applied to them.
Control Methods
Methods cause an object to do something 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.
For example, the MessageBox control has a method named Show, which is called
in the code snippet below:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
Control Events
Events are what happens when an object does something. An event is a
signal that informs an application that something important has occurred. For
example, when a user clicks a control on a form, the form can raise a Click event
and call a procedure that handles the event. There are various types of events
associated with a Form like click, double click, close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You
can see this code by double clicking the code which will give you a complete list
of the all events associated with Form control:

VB.Net By Prof.A.D.Chavan Page 3


Unit-IV

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
'event handler code goes here
End Sub
Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles
Load event. Similar way, you can check stub code for click, double click. If you
want to initialize some variables like properties, etc., then you will keep such code
inside Form1_Load() subroutine. Here, important point to note is the name of the
event handler, which is by default Form1_Load, but you can change this name
based on your naming convention you use in your application programming.
Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user
interface. Functionalities of all these controls are defined in the respective control
classes. The control classes are defined in the System.Windows.Forms namespace.
The following table lists some of the commonly used controls:
Forms:
The container for all the controls that make up the user interface. Visual Basic
Form is the container for all the controls that make up the user interface. Every
window you see in a running visual basic application is a form, thus the terms form
and window describe the same entity. Visual Studio creates a default form for you
when you create a Windows Forms Application. Every form will have title bar on
which the form's caption is displayed and there will be buttons to close, maximize
and minimize the form shown below.

VB.Net By Prof.A.D.Chavan Page 4


Unit-IV

If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from one
place to another place, to maximize or minimize the form or to close the form
Form Properties
Form has some impotent properties as fallows
1. AcceptButton:-The button that's automatically activated when you press Enter,
No matter which control has the focus at the time. Usually the
OK button on a form is set as Accept Button for a form.
2. CancelButton: - The button that's automatically activated when you hit the Esc
key. Usually, the Cancel button on a form is set as
CancelButton for a form.
3. BackColor:- Sets the form background color.
4 . Enabled:- If True, allows the form to respond to mouse and keyboard
events; if False, disables form.
5 .MinimizeBox:- By default, this property is True and you can set it to False
to hide the Minimize button on the title bar.
6 .MaximizeBox:- By default, this property is True and you can set it to False
to hide the Maximize button on the title bar.
7 .Name:- This is the actual name of the form.
8 .Text :- Text, which will appear at the title bar of the form.
Form Methods
The following are some of the commonly used methods of the Form class. :
1 Activate :- Activates the form and gives it focus.
2 ActivateMdiChild :- Activates the MDI child of a form.
3 Close :- Closes the form.
4 Contains :- Retrieves a value indicating whether the specified
control is a child of the control.
5 Focus :- Sets input focus to the control.
6 Show : - Displays the control to the user.
7 ShowDialog :- Shows the form as a modal dialog box.
Form Events
Events associated with forms control:
1 Click :- Occurs when the form is clicked.
2 Closed: - Occurs before the form is closed.
3 Closing:- Occurs when the form is closing.
4 DoubleClick: - Occurs when the form control is double-clicked.
VB.Net By Prof.A.D.Chavan Page 5
Unit-IV

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


6 Enter:- Occurs when the form is entered.
7 GotFocus:- Occurs when the form control receives focus.
8 KeyDown:- Occurs when a key is pressed while the form has focus.
9 KeyPress:- Occurs when a key is pressed while the form has focus.
10 KeyUp:- Occurs when a key is released while the form has focus.
Example:-
The following VB.Net source code shows how to change the Title, BackColor,
Size properties of Form1. Copy and paste the following VB.Net source code to
source code editor of your Visual Studio.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.Text = "Change Prperties Through Coding"
Me.BackColor = Color.Red
End Sub
End Class

 TextBox :
Text box controls allow entering text on a form at runtime. By default, it
takes a single line of text, however, you can make it accept multiple texts and
even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and
dropping it on the form.

VB.Net By Prof.A.D.Chavan Page 6


Unit-IV

 The Properties of the TextBox Control


The following are some of the commonly used properties of the TextBox control:
1.Font:- Gets or sets the font of the text displayed by the control.
2. FontHeight:- Gets or sets the height of the font of the control.
3 ForeColor:- Gets or sets the foreground color of the control.
4 PasswordChar:- Gets or sets the character used to mask characters of a
password in a single-line TextBox control.
5 ReadOnly:- Gets or sets a value indicating whether text in the text box is
read-only.
6 Text :- Gets or sets the current text in the TextBox.
7 TextAlign :- Gets or sets how text is aligned in a TextBox control. This
property has values: Left , Right ‘Center
8 TextLength:- Gets the length of text in the control.
 The Methods of the TextBox Control
The following are some of the commonly used methods of the TextBox control:
1 AppendText:- Appends text to the current text of a text box.
2 Clear:- Clears all text from the text box control.
3 Copy :- Copies the current selection in the text box to the Clipboard.
4 Cut:- Moves the current selection in the text box to the Clipboard.
5 Paste:- Replaces the current selection in the text box with the contents
of the Clipboard.
 Events of the TextBox Control
The following are some of the commonly used events of the Text control:
1 Click:- Occurs when the control is clicked.

VB.Net By Prof.A.D.Chavan Page 7


Unit-IV

2 DoubleClick:- Occurs when the control is double-clicked.


3 TextAlignChanged:- Occurs when the TextAlign property value changes.
Example
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim sum as Interger
Sum=Value(TextBox1.Text)+Value(TextBox.Text)
Textbox3.Text=Sum
End Sub
End sub
End Class
 Label: It represents a standard Windows label
The Label control represents a standard Windows label. It is generally used
to display some informative text on the GUI which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and
dropping it on the form.

Properties of the Label Control


The following are some of the commonly used properties of the Label control:
1.Autosize: Gets or sets a value specifying if the control should be automatically
resized to display all its contents.
2.BorderStyle:- Gets or sets the border style for the control.
3.Font:- Gets or sets the font of the text displayed by the control.
4.ForeColor:- Gets or sets the foreground color of the control.

VB.Net By Prof.A.D.Chavan Page 8


Unit-IV

5.Text:- Gets or sets the text associated with this control.


6.TextAlign:- Gets or sets the alignment of text in the label.
Methods of the Label Control
The following are some of the commonly used methods of the Label control:
1 Select:- Activates the control.
2.GetPreferredSize:- Retrieves the size of a rectangular area into which a control
can be fitted.
3. Refresh:- Forces the control to invalidate its client area and
immediately redraw itself and any child controls.
4 Show : - Displays the control to the user.
5 ToString :- Returns a String that contains the name of the control.
Events of the Label Control
The following are some of the commonly used events of the Label control:
1.AutoSize :- Changed Occurs when the value of the AutoSize property
changes.
2.Click:- Occurs when the control is clicked.
3.DoubleClick:- Occurs when the control is double-clicked.
4.GotFocus:- Occurs when the control receives focus.

Example
The following source code shows how to set some properties of the Label through
coding.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Label1.Text = "This is my first Label"
Label1.BorderStyle = BorderStyle.FixedSingle
Label1.TextAlign = ContentAlignment.MiddleCenter
End Sub
End Class
VB.Net Button Control
The Button control represents a standard Windows button. It is generally
used to generate a Click event by providing a handler for the Click event.
Let's create a label by dragging a Button control from the Toolbox ad
dropping it on the form.

VB.Net By Prof.A.D.Chavan Page 9


Unit-IV

Windows Forms controls are reusable components that encapsulate user


interface functionality and are used in client side Windows applications. A Button
is a control, which is an interactive component that enables users to communicate
with an application which we click and release to perform some actions.
The Button control represents a standard button that reacts to a Click event. A
Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the
button has focus. When you want to change display text of the Button , you can
change the Text property of the button.
Button1.Text = "My first Button"
Similarly if you want to load an Image to a Button control , you can code like this
Button1.Image = Image.FromFile("C:\testimage.jpg")
Properties of the Button Control
The following are some of the commonly used properties of the Button control:
1.AutoSizeMode:- Gets or Sets the mode by which the Button automatically
resizes itself.
2.BackColor:- Gets or sets the background color of the control.
3.BackgroundImage:-Gets or sets the background image displayed in the control.
4.DialogResult:- Gets or sets a value that is returned to the parent form when
the button is clicked. This is used while creating dialog
boxes.
5.ForeColor:- Gets or sets the foreground color of the control.
6.Image:- Gets or sets the image that is displayed on a button control.
7.Location:- Gets or sets the coordinates of the upper-left corner of the
control relative to the upper-left corner of its container.
VB.Net By Prof.A.D.Chavan Page 10
Unit-IV

8.TabIndex:- Gets or sets the tab order of the control within its container.
9.Text:- Gets or sets the text associated with this control.
Methods of the Button Control
The following are some of the commonly used methods of the Button control:
1. GetPreferredSize:- Retrieves the size of a rectangular area into which a control
can be fitted.
2. NotifyDefault:- Notifies the Button whether it is the default button so that it
can adjust its appearance accordingly.
3. Select :- Activates the control.
4. ToString:- Returns a String containing the name of the Component,
if any. This method should not be overridden.
Events of the Button Control
The following are some of the commonly used events of the Button control:
1.Click:- Occurs when the control is clicked.
2.DoubleClick:- Occurs when the user double-clicks the Button control.
3.GotFocus:- Occurs when the control receives focus.
4.TabIndexChanged:-Occurs when the TabIndex property value changes.
5.TextChanged:- Occurs when the Text property value changes.
6.Validated:- Occurs when the control is finished validating.
The following vb.net source code shows how to change the button Text
property while Form loading event and to display a message box when pressing a
Button Control.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Button1.Text = "Click Here"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MsgBox("WelCome")
End Sub
End Class
VB.Net ListBox controls.
ListBox: It represents a Windows control to display a list of items.

VB.Net By Prof.A.D.Chavan Page 11


Unit-IV

The ListBox represents a Windows control to display a list of items to a user. A


user can select an item from the list. It allows the programmer to add items at
design time by using the properties window or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and
dropping it on the form.

You can populate the list box items either from the properties window or at
runtime. To add items to a ListBox, select the ListBox control and get to the
properties window, for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box,
where you can enter the values one at a line.
Properties of the ListBox Control
The following are some of the commonly used properties of the ListBox control:
1.AllowSelection:- Gets a value indicating whether the ListBox currently
enables selection of list items.
2.BorderStyle:- Gets or sets the type of border drawn around the list box.
3.ColumnWidth:- Gets of sets the width of columns in a multicolumn list box.
4.HorizontalExtent:-Gets or sets the horizontal scrolling area of a list box.
5.HorizontalScrollBar:- Gets or sets the value indicating whether a horizontal
scrollbar is displayed in the list box.
6.ItemHeight:- Gets or sets the height of an item in the list box.
7.Items:- Gets the items of the list box.
8.MultiColumn:- Gets or sets a value indicating whether the list box
supports multiple columns.
9.ScrollAlwaysVisible:- Gets or sets a value indicating whether the vertical scroll

VB.Net By Prof.A.D.Chavan Page 12


Unit-IV

bar is shown at all times.


10.SelectedIndex:- Gets or sets the zero-based index of the currently selected
item in a list box.
11.SelectedIndices:- Gets a collection that contains the zero-based indexes of all
currently selected items in the list box.
12.SelectedItem:-Gets or sets the currently selected item in the list box.
13.SelectedItems:-Gets a collection containing the currently selected items in the
list box.
14.SelectedValue:-Gets or sets the value of the member property specified by the
ValueMember property.
15.SelectionMode:-Gets or sets the method in which items are selected in the list
box. This property has values:
 None
 One
 MultiSimple
 MultiExtended
16.Sorted:- Gets or sets a value indicating whether the items in the list box are
sorted alphabetically.
17.Text:- Gets or searches for the text of the currently selected item in the list
box.
18.TopIndex:-Gets or sets the index of the first visible item of a list box.
Methods of the ListBox Control
The following are some of the commonly used methods of the ListBox control
1.BeginUpdate:- Prevents the control from drawing until the EndUpdate method is
called, while items are added to the ListBox one at a time.
2.ClearSelected:-Unselects all items in the ListBox.
3.EndUpdate:-Resumes drawing of a list box after it was turned off by the
BeginUpdate method.
4.FindString:-Finds the first item in the ListBox that starts with the string
specified as an argument.
5.FindStringExact:-Finds the first item in the ListBox that exactly matches the
specified string.
6.GetSelected:-Returns a value indicating whether the specified item is selected.
7.SetSelected:-Selects or clears the selection for the specified item in a ListBox.
8.OnSelectedIndexChanged:-Raises the SelectedIndexChanged event.
9.OnSelectedValueChanged:-Raises the SelectedValueChanged event.
VB.Net By Prof.A.D.Chavan Page 13
Unit-IV

Events of the ListBox Control


The following are some of the commonly used events of the ListBox control:
1.Click:-Occurs when a list box is selected.
2.SelectedIndexChanged:-Occurs when the SelectedIndex property of a list box is
changed.
You can use the Add or Insert method to add items to a list box. The Add
method adds new items at the end of an unsorted list box. The Insert method
allows you to specify where to insert the item you are adding.
ListBox1.Items.Add("Sunday")
The SelectionMode property determines how many items in the list can be
selected at a time. A ListBox control can provide single or multiple selections
using the SelectionMode property.
If you want to retrieve a single selected item to a variable, you can code like this
Dim var As String
var = ListBox1.SelectedItem
If you change the selection mode property to multiple select , then you will
retrieve a collection of items from ListBox1.SelectedItems property.
ListBox1.SelectionMode = SelectionMode.MultiSimple
The following VB.Net program initially fill seven days in a week while in the
form load event and set the selection mode property to MultiSimple. At the Button
click.
Public Class Listbox
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Sunday")
ListBox1.Items.Add("Monday")
ListBox1.Items.Add("Tuesday")
ListBox1.Items.Add("Wednesday")
ListBox1.Items.Add("Thursday")
ListBox1.Items.Add("Friday")
ListBox1.Items.Add("Saturday")
End Sub

VB.Net By Prof.A.D.Chavan Page 14


Unit-IV

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


System.EventArgs) Handles Button1.Click
Dim var As String
var = ListBox1.SelectedItem
MsgBox(ListBox1.SelectedItem)
End Sub
End Class

ComboBox Control:-
The ComboBox control is used to display a drop-down list of various items.
It is a combination of a text box in which the user enters an item and a drop-down
list from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the
Toolbox and dropping it on the form.

VB.Net By Prof.A.D.Chavan Page 15


Unit-IV

You can populate the list box items either from the properties window or at
runtime. To add items to a ListBox, select the ListBox control and go to the
properties window for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box,
where you can enter the values one at a line.
Properties of the ComboBox Control
The following are some of the commonly used properties of the ComboBox
control:
1.AllowSelection:- Gets a value indicating whether the list enables selection of list
items.
2.AutoCompleteCustomSource:-Gets or sets a custom System.Collections.
Specialized.StringCollection to use when the
AutoCompleteSourceproperty is set to
CustomSource.
3.AutoCompleteMode:- Gets or sets an option that controls how automatic
completion works for the ComboBox.
4.AutoCompleteSource:-Gets or sets a value specifying the source of complete
strings used for automatic completion.
5.DataBindings:- Gets the data bindings for the control.
6.DataManager:- Gets the CurrencyManager associated with this control.
7.DataSource:- Gets or sets the data source for this ComboBox.
8.DropDownHeight:- Gets or sets the height in pixels of the drop-down portion
of the ComboBox.
VB.Net By Prof.A.D.Chavan Page 16
Unit-IV

9.DropDownStyle:- Gets or sets a value specifying the style of the combo box.
10.DropDownWidth:- Gets or sets the width of the of the drop-down portion of a
combo box.
11.DroppedDown:- Gets or sets a value indicating whether the combo box is
displaying its drop-down portion.
12.FlatStyle:- Gets or sets the appearance of the ComboBox.
13.ItemHeight:- Gets or sets the height of an item in the combo box.
14.Items:- Gets an object representing the collection of the items
contained in this ComboBox.
15.MaxDropDownItems:- Gets or sets the maximum number of items to be
displayed in the drop-down part of the combo box.
16.MaxLength:- Gets or sets the maximum number of characters a user can
enter in the editable area of the combo box.
17.SelectedIndex:- Gets or sets the index specifying the currently selected item.
18.SelectedItem:- Gets or sets currently selected item in the ComboBox.
19.SelectedText:- Gets or sets the text that is selected in the editable portion of a
ComboBox.
20.SelectedValue:-Gets or sets the value of the member property specified by the
ValueMember property.
21.SelectionLength:-Gets or sets the number of characters selected in the editable
portion of the combo box.
22.SelectionStart:- Gets or sets the starting index of text selected in the combo
box.
23.Sorted:- Gets or sets a value indicating whether the items in the combo
box are sorted.
24.Text:- Gets or sets the text associated with this control.
Methods of the ComboBox Control
The following are some of the commonly used methods of the ComboBox control:
1.BeginUpdate:-Prevents the control from drawing until the EndUpdate method is
called, while items are added to the combo box one at a time.
2.EndUpdate:-Resumes drawing of a combo box, after it was turned off by the
BeginUpdate method.
3.FindString:-Finds the first item in the combo box that starts with the string
specified as an argument.
4.FindStringExact:-Finds the first item in the combo box that exactly matches the
specified string.
VB.Net By Prof.A.D.Chavan Page 17
Unit-IV

5.SelectAll:-Selects all the text in the editable area of the combo box.
Events of the ComboBox Control
The following are some of the commonly used events of the ComboBox control:
1.DropDown:-Occurs when the drop-down portion of a combo box is displayed.
2.DropDownClosed:-Occurs when the drop-down portion of a combo box is no
longer visible.
3.DropDownStyleChanged:-Occurs when the DropDownStyle property of the
ComboBox has changed.
4.SelectedIndexChanged:-Occurs when the SelectedIndex property of a
ComboBox control has changed.
5.SelectionChangeCommitted:-Occurs when the selected item has changed and
the change appears in the combo box
The user can type a value in the text field or click the button to display a drop
down list. In addition to display and selection functionality, the ComboBox also
provides features that enable you to efficiently add items to the ComboBox.
Add item to combobox
ComboBox1.Items.Add("Sunday")
ComboBox1.Items.Add("Monday")
ComboBox1.Items.Add("Tuesday")
How to set the selected item in a comboBox
You can set which item should shown while it displaying in the form for first time.
ComboBox Example
The following VB.Net source code add seven days in a week to a combo box while
load event of a Windows Form and display the fourth item in the combobox.
Public Class Form2
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("Sunday")
ComboBox1.Items.Add("Monday")
ComboBox1.Items.Add("Tuesday")
ComboBox1.Items.Add("wednesday")
ComboBox1.Items.Add("Thursday")
ComboBox1.Items.Add("Friday")
ComboBox1.Items.Add("Saturday")
ComboBox1.SelectedItem = ComboBox1.Items(3)
End Sub
VB.Net By Prof.A.D.Chavan Page 18
Unit-IV

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


System.EventArgs) Handles Button1.Click
Dim var As String
var = ComboBox1.Text
MsgBox(var)
End Sub
End Class

CheckBox: It represents a Windows CheckBox.


The CheckBox control allows the user to set true/false or yes/no type options.
The user can select or deselect it. When a check box is selected it has the value
True, and when it is cleared, it holds the value False.
Let's create two check boxes by dragging CheckBox controls from the Toolbox
and dropping on the form.

VB.Net By Prof.A.D.Chavan Page 19


Unit-IV

The CheckBox control has three states, checked, unchecked and


indeterminate. In the indeterminate state, the check box is grayed out. To enable
the indeterminate state, theThreeState property of the check box is set to be True.
Properties of the CheckBox Control
The following are some of the commonly used properties of the CheckBox control:
1.Appearance:-Gets or sets a value determining the appearance of the check box.
2.AutoCheck:-Gets or sets a value indicating whether the Checked or
CheckedState value and the appearance of the control automatically change when
the check box is selected.
3.CheckAlign:-Gets or sets the horizontal and vertical alignment of the check
mark on the check box.
4.Checked:-Gets or sets a value indicating whether the check box is selected.
5.CheckState:-Gets or sets the state of a check box.
6.Text:-Gets or sets the caption of a check box.
7.ThreeState:-Gets or sets a value indicating whether or not a check box should
allow three check states rather than two.
Methods of the CheckBox Control
The following are some of the commonly used methods of the CheckBox control:
1.OnCheckedChanged:-Raises the CheckedChanged event.
2.OnCheckStateChanged:-Raises the CheckStateChanged event.
3.OnClick:-Raises the OnClick event.
Events of the CheckBox Control
The following are some of the commonly used events of the CheckBox control:

VB.Net By Prof.A.D.Chavan Page 20


Unit-IV

1.AppearanceChanged:-Occurs when the value of the Appearance property of the


check box is changed.
2.CheckedChanged:-Occurs when the value of the Checked property of the
CheckBox control is changed.
3.CheckStateChanged:-Occurs when the value of the CheckState property of the
CheckBox control is changed.
CheckBoxes allow the user to make multiple selections from a number of
options. You can click a check box to select it and click it again to deselect it.
CheckBoxes comes with a caption, which you can set in the Text property.
CheckBox1.Text = "BBA"
CheckBox2.Text = "BCA"
CheckBox3.Text = "BSC”
You can use the CheckBox control ThreeState property to direct the control to
return the Checked, Unchecked, and Indeterminate values. You need to set the
check boxs ThreeState property to True to indicate that you want it to support three
states.
CheckBox1.ThreeState = True
To apply the same property settings to multiple CheckBox controls, use the Style
property. The following VB.Net program shows how to find a checkbox is selected
or not.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim msg As String = " "
If CheckBox1.Checked = True Then
msg = "BBA"
End If
If CheckBox2.Checked = True Then
msg = msg & " " & "BCA"
End If
If CheckBox3.Checked = True Then
msg = msg & " " & "BSC"
End If
If msg.Length > 0 Then
MsgBox(msg & " " & "selected")
Else
VB.Net By Prof.A.D.Chavan Page 21
Unit-IV

MsgBox("No Checkbox selected")


End If
CheckBox1.ThreeState = True
End Sub
End Class

PictureBox:- It represents a Windows picture box control for displaying an


image.
The PictureBox control is used for displaying images on the form. The
Image property of the control allows you to set an image both at design time or at
run time.
Let's create a picture box by dragging a PictureBox control from the Toolbox
and dropping it on the form.

VB.Net By Prof.A.D.Chavan Page 22


Unit-IV

Properties of the PictureBox Control


The following are some of the commonly used properties of the PictureBox
control:
1.AllowDrop:- Specifies whether the picture box accepts data that a user drags on
it.
2.ErrorImage:- Gets or specifies an image to be displayed when an error occurs
during the image-loading process or if the image load is cancelled.
3.Image:- Gets or sets the image that is displayed in the control.
4.ImageLocation:-Gets or sets the path or the URL for the image displayed in the
control.
5.InitialImage:-Gets or sets the image displayed in the control when the main
image is loaded
6.SizeMode:-Determines the size of the image to be displayed in the control. This
property takes its value from the PictureBoxSizeMode enumeration, which has
values:
 Normal - the upper left corner of the image is placed at upper left part of the
picture box
 StrechImage - allows stretching of the image
 AutoSize - allows resizing the picture box to the size of the image
 CenterImage - allows centering the image in the picture box
 Zoom - allows increasing or decreasing the image size to maintain the size
ratio.
7.TabIndex:-Gets or sets the tab index value.

VB.Net By Prof.A.D.Chavan Page 23


Unit-IV

8.TabStop:-Specifies whether the user will be able to focus on the picture box by
using the TAB key.
9.Text:-Gets or sets the text for the picture box.
10.WaitOnLoad:-Specifies whether or not an image is loaded synchronously
Methods of the PictureBox Control
The following are some of the commonly used methods of the PictureBox control:
1.CancelAsync:-Cancels an asynchronous image load.
2.Load:-Displays an image in the picture box
3.LoadAsync:-Loads image asynchronously.
4.ToString:-Returns the string that represents the current picture box.
Events of the PictureBox Control
The following are some of the commonly used events of the PictureBox control:
1.CausesValidationChanged:-Overrides the Control.CausesValidationChanged
property.
2.Click:-Occurs when the control is clicked.
3.Enter:-Overrides the Control.Enter property.
4.FontChanged:-Occurs when the value of the Font property changes.
5.ForeColorChanged:-Occurs when the value of the ForeColor property changes.
6.KeyDown:-Occurs when a key is pressed when the control has focus.
7.KeyPress:-Occurs when a key is pressed when the control has focus.
8.KeyUp:-Occurs when a key is released when the control has focus.
9.Leave:-Occurs when input focus leaves the PictureBox.
10.LoadCompleted:-Occurs when the asynchronous image-load operation is
completed, been canceled, or raised an exception.
11.LoadProgressChanged:-Occurs when the progress of an asynchronous image-
loading operation has changed.
12.Resize:-Occurs when the control is resized.
13.RightToLeftChanged:-Occurs when the value of the RightToLeft property
changes.
14.SizeChanged:-Occurs when the Size property value changes.
15.SizeModeChanged:-Occurs when SizeMode changes.
16.TabIndexChanged:-Occurs when the value of the TabIndex property changes.
17.TabStopChanged:-Occurs when the value of the TabStop property changes.
18.TextChanged:-Occurs when the value of the Text property changes.

VB.Net By Prof.A.D.Chavan Page 24


Unit-IV

The Windows Forms PictureBox control is used to display images in


bitmap, GIF,icon, or JPEG formats.
You can set the Image property to the Image you want to display, either at
design time or at run time. You can programmatically change the image displayed
in a picture box, which is particularly useful when you use a single form to display
different pieces of information.
PictureBox1.Image = Image.FromFile("C:\testImage.jpg")
The SizeMode property, which is set to values in the PictureBoxSizeMode
enumeration, controls the clipping and positioning of the image in the display area.
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
There are five different PictureBoxSizeMode is available to PictureBox control.
AutoSize - Sizes the picture box to the image.
CenterImage - Centers the image in the picture box.
Normal - Places the upper-left corner of the image at upper
left in the picture box
StretchImage - Allows you to stretch the image in code
You can change the size of the display area at run time with the ClientSize
property.
pictureBox1.ClientSize = New Size(xSize, ySize)
The following VB.Net program shows how to load a picture from a file and display
it in streach mode.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
PictureBox1.Image = Image.FromFile("d:\virat.jpg")
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub
End Class

VB.Net By Prof.A.D.Chavan Page 25


Unit-IV

Image Controls
As you can guess from its name, you use Image controls to display images in
Web applications. You set the URL of the image with the ImageUrl property. The
alignment of the image in relation to other elements on the Web page is specified
by setting ImageAlign property You can specify the text to display in place of an
image if the image is not available by setting the AlternateText property.

Figure:- Using an Image control.


There's not really all that much going on in Image controls—they're simply
translated to <img> elements. Here's the HTML that displays the image in Figure
17.1:
<img id="Image1" src="Image.jpg" border="0" style="height:150px;width:
300px;Z-INDEX: 101; LEFT: 107px; POSITION: absolute; TOP: 73px" />
RadioButton Control
The RadioButton control is used to provide a set of mutually exclusive
options. The user can select one radio button in a group. If you need to place more
than one group of radio buttons in the same form, you should place them in
different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the
Toolbox and dropping on the form.

VB.Net By Prof.A.D.Chavan Page 26


Unit-IV

The Checked property of the radio button is used to set the state of a radio
button. You can display text, image or both on radio button control. You can also
change the appearance of the radio button control by using the Appearance
property.
Properties of the RadioButton Control
The following are some of the commonly used properties of the RadioButton
control:
1.Appearance:-Gets or sets a value determining the appearance of the radio
button.
2.AutoCheck:-Gets or sets a value indicating whether the Checked value and the
appearance of the control automatically change when the control is clicked.
3.CheckAlign:-Gets or sets the location of the check box portion of the radio
button.
4.Checked:-Gets or sets a value indicating whether the control is checked.
5.Text:-Gets or sets the caption for a radio button.
6.TabStop:- Gets or sets a value indicating whether a user can give focus to the
RadioButton control using the TAB key.
Methods of the RadioButton Control
The following are some of the commonly used methods of the RadioButton
control:
1 PerformClick:- Generates a Click event for the control, simulating a click by a
user.
Events of the RadioButton Control
The following are some of the commonly used events of the RadioButton control:
1 AppearanceChanged:-Occurs when the value of the Appearance property of the
RadioButton control is changed.
2 CheckedChanged:-Occurs when the value of the Checked property of the
RadioButton control is changed.
A radio button or option button is a type of graphical user interface element
that allows the user to choose only one of a predefined set of options. When a user
clicks on a radio button, it becomes checked, and all other radio buttons with same
group become unchecked.
The radio button and the check box are used for different functions. Use a
radio button when you want the user to choose only one option. When you want
the user to choose all appropriate options, use a check box. Like check boxes, radio

VB.Net By Prof.A.D.Chavan Page 27


Unit-IV

buttons support a Checked property that indicates whether the radio button is
selected.
Public Class Form1
Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
Label1.ForeColor = Color.Red
End Sub
Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
Label1.ForeColor = Color.Green
End Sub
Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
Label1.ForeColor = Color.Blue
End Sub
End Class

Panel Control in VB.NET


The Panel control is a container control that is used to host a group of similar
child controls. One of the major uses I found for a Panel control when you have to
show and hide a group of controls. Instead of show and hide individual controls,
you can simply hide and show a single Panel and all child controls.
We will demonstrate how to create and use a Panel control in a Windows Forms
application.
Creating a Panel
We can create a Panel control using the Forms designer at design-time or using
the Panel class in code at run-time.

VB.Net By Prof.A.D.Chavan Page 28


Unit-IV

Design-time
To create a Panel control at design-time, you simply drag and drop a Panel
control from Toolbox to a Form in Visual Studio. After you drag and drop a Panel
on a Form, the Panel looks like Figure. Once a Panel is on the Form, you can move
it around and resize it using mouse and set its properties and events.

Run-time
Creating a Panel control at run-time is merely a work of creating an instance of
Panel class, set its properties and adds Panel class to the Form controls.
First step to create a dynamic Panel is to create an instance of Panel class. The
following code snippet creates a Panel control object.
Dim dynamicPanel As New Panel()
In the next step, you may set properties of a Panel control. The following code
snippet sets location, size and Name properties of a Panel.
dynamicPanel.Location = New System.Drawing.Point(26, 12)
dynamicPanel.Name = "Panel1"
dynamicPanel.Size = New System.Drawing.Size(228, 200)
dynamicPanel.BackColor = Color.LightBlue
Once the Panel control is ready with its properties, the next step is to add the
Panel to a Form. To do so, we use Form.Controls.Add method that adds Panel
control to the Form controls and displays on the Form based on the location and
size of the control. The following code snippet adds a Panel control to the current
Form.
Controls.Add(dynamicPanel)
Setting Panel Properties
After you place a Panel control on a Form, the next step is to set its properties. The
easiest way to set properties is from the Properties Window. You can open

VB.Net By Prof.A.D.Chavan Page 29


Unit-IV

Properties window by pressing F4 or right click on a control and select Properties


menu item. The Properties window looks like in Figure.

Panel has most of the common control properties. Here I am going to discuss
the main purpose of a Panel.
Adding Controls to a Panel
You can add controls to a Panel by dragging and dropping control to the
Panel. We can add controls to a Panel at run-time by using its Add method. The
following code snippet creates a Panel, creates a TextBox and a CheckBox and
adds these two controls to a Panel.
Private Sub CreateButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles CreateButton.Click
Dim dynamicPanel As New Panel()
dynamicPanel.Location = New System.Drawing.Point(26, 12)
dynamicPanel.Name = "Panel1"
dynamicPanel.Size = New System.Drawing.Size(228, 200)
dynamicPanel.BackColor = Color.LightBlue
Dim textBox1 As New TextBox()
textBox1.Location = New Point(10, 10)
textBox1.Text = "I am a TextBox5"
textBox1.Size = New Size(200, 30)
Dim checkBox1 As New CheckBox()
checkBox1.Location = New Point(10, 50)
checkBox1.Text = "Check Me"
checkBox1.Size = New Size(200, 30)

VB.Net By Prof.A.D.Chavan Page 30


Unit-IV

dynamicPanel.Controls.Add(textBox1)
dynamicPanel.Controls.Add(checkBox1)
Controls.Add(dynamicPanel)
End Sub
The output looks like Figure .

Show and Hide a Panel


I have seen in many applications when you want to show and hide a group of
controls on a Form based on some condition. That is where a Panel is useful.
Instead of show and hide individual controls, we can group controls that we want
to show and hide and place them on two different Panels and show and hide the
Panels. To show and hide a Panel, we use Visible property.
dynamicPanel.Visible = False.
Timer Control
Timer Control plays an important role in the Client side programming and
Server side programming, also used in Windows Services. By using this Timer
Control, windows allow you to control when actions take place without the
interaction of another thread.
Use of Timer Control We can use Timer Control in many situations in our
development environment. If you want to run some code after a certain interval of
time continuously, you can use the Timer control. As well as to start a process at a
fixed time schedule, to increase or decrease the speed in an animation graphics
with time schedule etc. you can use the Timer Control. The Visual Studio toolbox
has a Timer Control that allowing you to drag and drop the timer controls directly
onto a Windows Forms designer. At runtime it does not have a visual
representation and works as a component in the background.

VB.Net By Prof.A.D.Chavan Page 31


Unit-IV

Properties of Timer Controls


Enabled: - Property used to Get or set whether the timer is running.
Interval:- Property used to set or get the time in millisecond between the timer
clicks.( 1 second is equal to 1000 milliseconds).
Methods of Timer Controls
Start:- Method used to start timer.
Stop:- Method used to stop timer.
Events of Timer Controls
Tick:- Triggered when the time intreval has elapsed.
Menu
Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes
were used for adding menus, sub-menus and context menus in a Windows
application.
Now, the MenuStrip, the ToolStripMenuItem, ToolStripDropDown and
ToolStripDropDownMenu controls replace and add functionality to the Menu-
related controls of previous versions. However, the old control classes are retained
for both backward compatibility and future use.
Let us create a typical windows main menu bar and sub menus using the
old version controls first since these controls are still much used in old
applications.
Following is an example, which shows how we create a menu bar with menu
items: File, Edit, View and Project. The File menu has the sub menus New, Open
and Save.
Let's double click on the Form and put the following code in the opened window.
Public Class Form 1
Private Sub Form 1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
'defining the main menu bar
Dim m nuBar As New MainMenu()
'defining the menu item s for the m ain menu bar
Dim myMenuItem File As New MenuItem ("&File")
Dim myMenuItem Edit As New MenuItem ("&Edit")

VB.Net By Prof.A.D.Chavan Page 32


Unit-IV

Dim myMenuItem View As New MenuItem ("&View")


Dim myMenuItem Project As New MenuItem ("&Project")
'adding the menu item s to the main menu bar
m nuBar.MenuItem s.Add(myMenuItem File)
m nuBar.MenuItem s.Add(myMenuItem Edit)
m nuBar.MenuItem s.Add(myMenuItem View)
m nuBar.MenuItem s.Add(myMenuItem Project)
' defining some sub menus
Dim myMenuItem New As New MenuItem ("&New")
Dim myMenuItem Open As New MenuItem ("&Open")
Dim myMenuItem Save As New MenuItem ("&Save")
'add sub m enus to the File m enu
myMenuItem File.MenuItem s.Add(myMenuItem New)
myMenuItem File.MenuItem s.Add(myMenuItem Open)
m yMenuItem File.MenuItem s.Add(myMenuItem Save)
'add the main menu to the form
Me.Menu = mnuBar
' Set the caption bar text of the form .
Me.Text = "HVPM "
End Sub
End Class
When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:

Windows Forms contain a rich set of classes for creating your own custom
menus with modern appearance, look and feel. The MenuStrip,

VB.Net By Prof.A.D.Chavan Page 33


Unit-IV

ToolStripMenuItem, ContextMenuStrip controls are used to create menu bars and


context menus efficiently.
Following are the controls used to crate menu with description
1.MenuStrip:-It provides a menu system for a form.
2.ToolStripMenuItem:-It represents a selectable option displayed on a MenuStrip
or ContextMenuStrip. The ToolStripMenuItem control replaces and adds
functionality to the MenuItem control of previous versions.
3.ContextMenuStrip:-It represents a shortcut menu.
The Built-in Dialog Boxes
There are a number of built-in dialog boxes in Visual Basic, which is great,
because developing your own file open, file save, and other dialog boxes not only
takes a lot of work, but gives your program a different look from what Windows
users are already used to. We'll look at these dialogs ; here they are:
 Open File dialogs
 Save File dialogs
 Font dialogs
 Color dialogs
 Print Preview dialogs
 Page Setup dialogs
 Print dialogs
You use the ShowDialog method to display the dialog at run time and can
check its return value (such as DialogResult.OK or DialogResult.Cancel) to see
which button the user has clicked. Here are the possible return values from this
method, from the DialogResult enumeration:
 Abort:-The dialog box return value is Abort (usually from a button labeled
Abort).
 Cancel:- The dialog box return value is Cancel (usually from a button
labeled Cancel).
 Ignore:- The dialog box return value is Ignore (usually from a button
labeled Ignore).
 No:-The dialog box return value is No (usually from a button labeled No).
 None:- Nothing is returned from the dialog box. This means that the modal
dialog continues running.
 OK:- The dialog box return value is OK (usually from a button labeled
OK).

VB.Net By Prof.A.D.Chavan Page 34


Unit-IV

 Retry:-The dialog box return value is Retry (usually from a button labeled
Retry).
 Yes:-The dialog box return value is Yes (usually from a button labeled Yes).
I'll take a closer look at these dialogs now.
Open File Dialogs
As you'd expect from its name, the Open File dialog lets the user select a file to
open. In fact, it's the same Open File dialog used by Windows itself. You can see
this dialog box in Figure 1, as displayed in the OpenFileDialog .

Figure 1: An Open File dialog box.


Open File dialogs are supported with the OpenFileDialog class. You can let
users select multiple files with the Multiselect property. You can use the
ShowReadOnly property to determine if a read-only checkbox appears in the
dialog box. The ReadOnlyChecked property indicates whether the read-only
checkbox is selected. And the Filter property sets the current file name filter
string, which determines the choices that appear in the "Files of type" box in the
dialog box. The name and path the user selected is stored in the FileName property
of the OpenFileDialog object—and there's a neat shortcut here: you can use the
OpenFile method to open the selected file directly.

Save File Dialogs


Save File dialogs are supported by the SaveFileDialog class. These dialogs
let the user specify the name of a file to save data to. These dialogs are the same as
the standard Save File dialog box used by Windows; you can see a Save File dialog
in Figure 2 from the SaveFileDialog .

Figure 2: A Save As dialog box

VB.Net By Prof.A.D.Chavan Page 35


Unit-IV

You can use the ShowDialog method to display the dialog box at run
time. You can use the FileName property to get the file the user selected, open a
file in read-write mode using the OpenFile method, and so on.
You also can set the handy CheckFileExists and CheckPathExists
properties to True to check if a specified file or path already exists, and if it should
be created otherwise.
Font Dialogs
Font dialogs let the user select a font size, face, color, and so on. You can see
a font dialog box at work in Figure 3 from the FontDialog .

Figure 3: A font dialog box.


What's handy about these dialogs, besides the fact that they're the same as
those used by Windows, is that they return Font and Color objects directly (using
the properties of the same name), ready for installation in controls that can use
them, like rich text boxes. This saves you the trouble of creating and configuring
these objects from scratch.
To display the font dialog box, call the ShowDialog method. This dialog
shows list boxes for Font, Style, and Size, checkboxes for effects like Strikeout
and Underline, a drop-down list for Script (Script refers to different character
scripts that are available for a given font—for example, Hebrew), and a sample of
how the font will appear. You can recover these settings using properties of the
same names of the Font object returned by the Font property.
Color Dialogs
Color dialogs let the user select a color in an easy way. The principal
property you use of these dialogs is the Color property, which returns a Color
object, ready for use. You can see a color dialog box at work in Figure 4.

VB.Net By Prof.A.D.Chavan Page 36


Unit-IV

Figure 4: A color dialog box.


In Figure 4, I've opened the color dialog fully (by clicking Define Custom
Colors) to let the user define their own colors with color values and hue, saturation,
and luminosity. If you set the AllowFullOpen property to False, on the other hand,
the Define Custom Colors button is disabled and the user can select colors only
from the predefined colors in the palette. Note also that if you set the
SolidColorOnly property to True, the user can select only solid (not dithered)
colors.
Printing Documents
The way you print documents in Visual Basic has become fairly involved,
revolving around the PrintDocument class. You add an object of this class to a
project, and then handle events like PrintPage, which is called every time a new
page is to be printed. When it is added to a form, the PrintDocument component
appears in the tray at the bottom of the Windows form designer.
You're responsible for handling the printing yourself-you are passed a
Graphics object, and you use the methods of that object, like DrawString, which
draws strings of text, to draw the document you want printed. Because this
graphics object corresponds to the printer, what you draw with it will appear in the
printer.
For some reason, all the examples you see on this topic only print out a
single page, so I'll make it a point here to show how you handle multipage
documents as well. You'll find Print, Print Preview, and Page Setup menu items in
that example's File menu.Besides PrintDocument objects, there are a number of
dialog boxes you use to support printing. The first of these is the Print dialog itself.
Print Dialogs
Print dialogs let the user print documents, and these dialogs are supported
with the PrintDialog class. Before displaying a Print dialog, you set the
Document property of a PrintDialog object to a PrintDocument object, and the
PrinterSettings property to a PrinterSettings object of the kind set by Page Setup
dialogs.When the dialog is closed, you can print the document by assigning the

VB.Net By Prof.A.D.Chavan Page 37


Unit-IV

PrintDialog object's PrinterSettings property (which returns a PrinterSettings


object as configured by the user, indicating the number of copies to print, the
printer to use, and so on) to the PrinterSettings property of the PrintDocument
object and use the PrintDocument object's Print method to actually print the
document. Here's how that might look in code:
Private Sub MenuItem1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MenuItem1.Click
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
PrintDocument1.Print()
End If
End Sub
You can see a Print dialog in Figure5 —this one comes from the Printing.

Figure 5: The Print dialog.


Print Preview Dialogs
You use Print Preview dialogs to let the user see what a document will look
like when it's printed. This dialog is supported with the PrintPreviewDialog class.
This dialog contains buttons for printing, zooming in, displaying one or multiple
pages, and closing the dialog box. You can see it at work in Figure 6.from the
Printing .

VB.Net By Prof.A.D.Chavan Page 38


Unit-IV

Figure 6: The Print Preview dialog.


The dialog's major property is Document, which sets the document to be
previewed, and the document must be a PrintDocument object. There's not much
else to do here—this dialog simply displays the document as it will be printed.
Print Preview dialogs are based on the PrintPreviewControl object (see the next
topic), and you can set some of the properties of that control directly, such as the
Columns and Rows properties (which set the number of pages displayed
horizontally and vertically) with properties like.
PrintPreviewDialog1.PrintPreview Control.Columns or
PrintPreviewDialog1.PrintPreview Control.Rows.
You also can use PrintPreviewControl objects directly to create your own
custom print preview dialog boxes.
Custom Print Previews
You can use a PrintPreviewControl to display a PrintDocument as it
will appear when printed. Note that this control has no buttons or other user
interface elements, so you usually use this control only if you wish to write your
own print preview user interface. You can see a print preview control at work in
Figure 7 from the Printing . Here, the control is showing the first page that the
Printing example prints out, which just displays a red rectangle.

Figure 7: A Print Preview control

VB.Net By Prof.A.D.Chavan Page 39


Unit-IV

Page Setup Dialogs


You also can use Page Setup dialogs to specify page details for printing. You
can let users set border and margin adjustments, headers and footers, and portrait
or landscape orientation, and so on. You can see a Page Setup dialog in Figure 8
from the Printing .

Figure 8: A Page Setup dialog.


You can use the PrinterSettings property of this dialog box to get a Printer
Settings object that holds the settings that the user specified, and assign that object
to a PrintDocument object's PrinterSettings property to make sure the settings
the user wants are assigned to the document itself. Here's how that might look in
code:
Private Sub MenuItem2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MenuItem2.Click
PageSetupDialog1.Document = PrintDocument1
PageSetupDialog1.PrinterSettings = PrintDocument1.PrinterSettings
If PageSetupDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.PrinterSettings = PageSetupDialog1.PrinterSettings
End If
End Sub

VB.Net By Prof.A.D.Chavan Page 40

You might also like