Unit - 2 VB
Unit - 2 VB
VB.NET
The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-level,
object-oriented programming language developed by Microsoft in 2002. It is a successor of
Visual Basic 6.0, that is implemented on the Microsoft .NET framework. Furthermore, it
supports the OOPs concept, such as abstraction, encapsulation, inheritance, and polymorphism.
Therefore, everything in the VB.NET language is an object, including all primitive data types
(Integer, String, char, long, short, Boolean, etc.), user-defined data types, events, and all objects
that inherit from its base class. It is not a case sensitive language, whereas, C++, Java, and C# are
case sensitive language.
Applications built using the VB.NET language are very reliable and scalable, relying on the
.NET Framework to access all libraries that help to execute a VB.NET program. With this
language, you can develop a fully object-oriented application that is similar to an application
created through another language such as C++, Java, or C#. In addition, applications or programs
of VB.NET are not only running on the window operating system but can also run on Linux or
Mac OS.
VB.NET Features
1. Picture Box:-With the Windows Forms PictureBox control, you can load and display a picture
on a form at design time by setting the Image property to a valid picture. Acceptable file types
include:
Bitmap .bmp
Icon .ico
GIF .gif
Metafile .wmf
JPEG .jpg
Dim Statement
Declaration of Variable
Parts
Public
Optional. Variables declared with the Public keyword have public access. There are no
restrictions on the accessibility of public variables.
You can use Public only at module, namespace, or file level. This means you can declare
public variables in a source file or inside a module, class, or structure, but not inside a
procedure. If you specify Public, you can optionally omit the Dim keyword.
Protected
Optional. Variables declared with the Protected keyword have protected access. They are
accessible only from within their own class or from a derived class. Protected access is not a
superset of friend access.
You can use Protected only at class level. This means you can declare protected
variables inside a class but not inside a procedure, and not at module, namespace, or file
level. You can use Protected only to declare members of the class. If you specify
Protected, you can optionally omit the Dim keyword.
Private
Optional. Variables declared with the Private keyword have private access. They are accessible
only from within their declaration context, including from members of any nested types such as
procedures.
You can use Private only at module level. This means you can declare private variables
inside a module, class, or structure, but not at namespace or file level and not inside a
procedure. If you specify Private, you can optionally omit the Dim keyword.
Static
Optional. Variables declared with the Static keyword remain in existence and retain their latest
values after termination of the procedure in which they are declared.
You can use Static only at procedure level. This means you can declare static variables
inside a procedure or a block within a procedure, but not at class or module level. If you
specify Static, you can optionally omit the Dim keyword.
You cannot specify Static together with either Shared or Shadows in the same variable
declaration.
varname
Required. Name of the variable. Must be a valid Visual Basic identifier. You can declare as many
variables as you like in the same declaration statement, specifying the name part for each one
and supplying the boundlist part for arrays. Multiple variables are separated by commas.
You can declare several variables to be of the same data type. You can also specify
different types for different variables or groups of variables. Each variable takes the data
type specified in the first As clause encountered after its name part.
New
Optional. Keyword that enables immediate creation of an object. If you use New when declaring
the object variable, a new instance of the object is created when the Dim statement is executed.
type
Optional unless Option Strict is On. Data type of the variable. Can be Boolean, Byte, Char, Date,
Decimal, Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration,
structure, class, or interface. You can use a separate As clause for each variable being defined,
or you can define several variables to be of the same type by using a common As clause.
The Dim statement can declare the data type of a variable and initialize its contents. The
declaration statements in the following example declare an Integer variable, a Boolean variable,
and an object variable. These are initialized, respectively, to 10, True, and a newly created
instance of the Label class.
If you do not specify an initialization value for a variable, Visual Basic initializes it to the default
value for its data type. The default initialization values are as follows:
This example uses the Dim statement to declare variables and arrays. The lower bound for array
subscripts is always 0, and the upper bound is the value that appears in the Dim statement.
Data Types
The following table shows the Visual Basic .NET data types, their supporting common language runtime
types, their nominal storage allocation, and their value ranges.
Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object.
User-Defined (inherits from Depends on Each member of the structure has a range determined
Type System.ValueType) implementing by its data type and independent of the ranges of the
(structure) platform other members.
Decimal variables are stored as signed 128-bit (16-byte) integers scaled by a variable power of 10. The
scaling factor specifies the number of digits to the right of the decimal point . the D type character to
assign a large value to a Decimal variable or constant, as the following example shows:
textBox1.Copy()
2. Cut-> This method will only cut text from the text box if text is
selected in the control. You can use this method, instead of using the
Clipboard class, to copy text in the text box and move it to the
Clipboard.
3. Paste -> The Paste method will only paste text into the control if text is currently
stored in the Clipboard. Once your application exits, any content stored in the Clipboard
is removed.
4. Hide -> Hiding the control is equivalent to setting the Visible property to false. After
the Hide method is called, the Visible property returns a value of false until the Show
method is called.
5. Clear->You can use this method to clear the contents of the control instead of assigning the
Text property an empty string.
Public Events:-
Keypress Occurs when a key is pressed while the control has focus.
When a Windows Forms TextBox control first receives the focus, the default insertion within the
text box is to the left of any existing text. The user can move the insertion point with the
keyboard or the mouse. If the text box loses and then regains the focus, the insertion point will be
wherever the user last placed it.
In some cases, this behavior can be disconcerting to the user. In a word processing application, the user
might expect new characters to appear after any existing text. In a data entry application, the user might
expect new characters to replace any existing entry. The SelectionStart and SelectionLength properties
allow you to modify the behavior to suit your purpose.
1. Set the SelectionStart property to an appropriate value. Zero places the insertion point
immediately to the left of the first character.
2. (Optional) Set the SelectionLength property to the length of the text you want to select.
The Items, Selected Items, and Selected Indices properties provide access to the three collections that
are used by the ListBox. The following table outlines the three collections used by the ListBox and their
use within the control.
1. SelectedIndex : Gets or sets the zero-based index of the currently selected item in a List
Box. A value of negative one (-1) is returned if no item is selected.
2. Items : A ListBox.ObjectCollection representing the items in the List Box. This property enables
you to obtain a reference to the list of items that are currently stored in the ListBox.
3. SelectedItem : An object that represents the current selection in the control. For a standard
ListBox, you can use this property to determine which item is selected in the ListBox. If the
SelectionMode property of the ListBox is set to either SelectionMode.MultiSimple or
SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items
are selected in the list, this property can return any selected item.
4. Selected Indices : A ListBox.SelectedIndexCollection containing the indexes of the currently
selected items in the control. If no items are currently selected, an empty
ListBox.SelectedIndexCollection is returned.For a multiple-selection ListBox, this property returns
a collection containing the indexes to all items that are selected in the ListBox. For a single-
selection ListBox, this property returns a collection containing a single element containing the
index of the only selected item in the ListBox. For more information on how to manipulate the
items of the collection, see ListBox.SelectedIndexCollection.
5. MultiColumn: true if the list box supports multiple columns; otherwise, false. The default is false.
A multicolumn list box places items into as many columns as are needed to make vertical scrolling
unnecessary.
6. SelectionMode : The SelectionMode property enables you to determine how many items in the
List Box a user can select at one time and how the user can make multiple-selections. When the
SelectionMode property is set to SelectionMode.MultiExtended, pressing SHIFT and clicking the
mouse or pressing SHIFT and one of the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW,
and RIGHT ARROW) extends the selection from the previously selected item to the current item.
Pressing CTRL and clicking the mouse selects or deselects an item in the list. When the property is
set to SelectionMode.MultiSimple, a mouse click or pressing the SPACEBAR selects or deselects
an item in the list.
7. Count : Gets the number of items in the collection.
8. Item : Property Value An object representing the item located at the specified index within the
collection.
9. Sorted : Windows Forms controls do not sort when they are data-bound. To display sorted data,
use a data source that supports sorting and then have the data source sort it. If the control is not
data-bound, then setting the Sorted property to true repositions all existing list items in sorted
order.
Public Methods
1. ClearSelected : Calling this method is equivalent to setting the Selected Index
property to negative one (-1). You can use this method to quickly remove unselect all
items in the list.
2. Dispose = Releases the resources used by the Component
3. Add.Item : Adding Items from a ListBox Control Items can be added to a Windows Forms list
box in a variety of ways, since these controls can be bound to a variety of data sources.
ComboBox1.Items.Add ("Tokyo")
Insert the string or object at the desired point in the list with the Insert method:
4. To remove an item
Remove has one argument that specifies the item to remove. RemoveAt removes the
item with the specified index number.
5. List. Clear : When you remove items from the list, all information about the deleted items is
lost. To remove a single item from the List Box, use the Remove or Remove At method.
Common Events
1. SelectedIndexChanged= you can create an event handler for this event to determine when the
selected index in the List Box has been changed. This can be useful when you need to display
information in other controls based on the current selection in the ListBox.
2. DoubleClick Event =Occurs when the control is double-clicked.
3. Enter= Occurs when the control is entered.
4. Leave Occurs when the input focus leaves the control.
5. Keypress= Occurs when a key is pressed while the control has focus
6. Working with ListBoxes :
The SelectedIndex property returns an integer value that corresponds to the selected list item.
You can programmatically change the selected item by changing the SelectedIndex value in
code; the corresponding item in the list will appear in the text box portion of the combo box. If
no item is selected, the SelectedIndex value is -1. If the first item in the list is selected, then the
SelectedIndex value is 0. The SelectedItem property is similar to SelectedIndex, but returns the
item itself, usually a string value. The Items.Count property reflects the number of items in the
list, and the value of the Items.Count property is always one more than the largest possible
SelectedIndex value because SelectedIndex is zero-based.
To add or delete items in a ListBox control, use the Items.Add, Items.Insert, Items.Clear or
Items.Remove method. Alternatively, you can add items to the list by using the Items property in the
designer.
Properties
1. Items Gets an object representing the collection of the items contained in this Combo Box
This property enables you to obtain a reference to the list of items that are currently stored in
the Combo Box. With this reference, you can add items, remove items, and obtain a count of the
items in the collection.
Example
comboBox1.Items.Add (textBox1.Text)
End Sub
2 SelectedItem : An object that represents the current selection in the control. For a standard List
Box, you can use this property to determine which item is selected in the ListBox. If the
Selection Mode property of the ListBox is set to either SelectionMode.MultiSimple or
SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items
are selected in the list, this property can return any selected item.
3. SelectedIndex : Gets or sets the zero-based index of the currently selected item in a List Box. A
value of negative one (-1) is returned if no item is selected.
4. Sorted : Windows Forms controls do not sort when they are data-bound. To display sorted data,
use a data source that supports sorting and then have the data source sort it. If the control is
not data-bound, then setting the Sorted property to true repositions all existing list items in
sorted order.
Generally, a combo box is appropriate when there is a list of suggested choices, and a list box is
appropriate when you want to limit input to what is on the list. A combo box contains a text box
field, so choices not on the list can be typed in. The exception is when the DropDownStyle
property is set to ComboBoxStyle.DropDownList. In that case, the control will select an item if
you type its first letter.
In addition, combo boxes save space on a form. Because the full list is not displayed until the
user clicks the down arrow, a combo box can easily fit in a small space where a list box would
not fit. An exception is when the DropDownStyle property is set to ComboBoxStyle.Simple:
the full list is displayed, and the combo box takes up more room than a list box would.
The Label
The Label as name implies a sticker on that some thing can be written. The
same is with this control. This is used to give a description to the control to
which it is described. It in most cases come with a combination. Like when you
create a check box it accompanies a label. Label controls also prompt you to
perform an action though in rare cases. The caption for a label is stored in the
Text property. Because you can change that caption in code, labels can act a
little like no editable text boxes, displaying text and messages to the user. The
Text Align ((formerly Alignment) property allows you to set the alignment of
the text within the label.
The Chekbox
The checkbox is a control that you may use to select one more choices among
many. You can select all even. You click a checkbox to select it, and click it
again to deselect it. When you select a checkbox, a check appears in it,
indicating that the box is indeed selected. You use a checkbox to give the user
an option, such as true/false or yes/no. The checkbox control supports two or
three states. For standard checkboxes, you use the checked property to get or
set the value of a checkbox control, but for three-state checkboxes, which
support an “indeterminate” state, you use the Check state property. The
indeterminate state is sort of a middle state between checked and unchecked.
Auto Check Specifies if the Checked or Check state values and the checkbox’s appearance are
automatically changed when the checkbox is clicked.
Check Align Gets/sets the horizontal and vertical alignment of a checkbox in a checkbox control.
Image Index Gets/sets the image list index value of the image displayed in the checkbox.
Image List Gets/sets the Image List that contains the image displayed in a checkbox.
Property Means
Appearance Gets/sets the value that determines the appearance of the radio
button.
AutoCheck Gets/sets a value indicating whether the Checked value and the
appearance of the/ control automatically change when the radio
button is clicked.
ImageIndex Gets/sets the image list index value of the image displayed in a
radio button.
Here’s an example showing how to determine whether a radio button is selected or not.
In this case, we display a message in a message box that indicates if a radio button,
RadioButton1, is selected or not:
Private Sub Button1_Click (Byva1 sender As System.Object, Byva1e As System. Event Args)
Hand1es
Button1. Click
Else
End If
End Sub
Property Means
Border style Gets/sets the tree view’s border style.
Check boxes Gets/ sets whether checkboxes should be displayed next to tree
nodes
Image index Gets/sets the image list index of the current image.
Image list Gets/ sets the image list used with this tree view.
Path separator Gets/ sets the string the tree node uses as a path delimiter.
Scrollable Gets/sets whether the tree view should display scroll bars as needed.
Selectedimage index Gets/sets the image index for the image to display when a node is
selected.
Event means
After check Occurs when a node check box is checked.
After label edit Occurs when a tree node label text is edited.
Item drag Occurs when an item is dragged into the tree view.
Toolbar control:
Toolbars are seen in almost every application, and gives users quick access to regularly
used features such as save. Microsoft offers a toolbar control in its common controls, which
makes it very easy to add a toolbar to your own application. To add a toolbar to the top of your
form, expand the toolbox and locate the toolbar control (you may have to scroll down to see it)
double click the toolbar control, and it will be added to the top of your form. However, there’s
not much to see, at the moment, toolbars work by adding buttons and images to them. The
button is that clicked, and an action performed. Click on your Toolbar to select it. In the
property box for the Toolbar, you’ll notice that it has the default Name of ToolBarl. We’ll keep
this Name. But locate the Buttons (Collection) property, and click the button with the three
dots in it. This brings up the toolBarButton Collection Editor. To add a new button to your
toolbar, click the add button:
Each button on the toolbar has it’s own properties and methods. The button you have
just added has a default Name of ToolBarButtonl. This is not terribly descriptive. What we’re
giving to do is add three toolbar buttons: one to create a new file, one to open a file, and one to
save a file. So,
Click the Name property and change it to tbrFileNew
Then click OK
LinkLabel Class:
The LinkLabel control is similar to a Label control with the exception that is can display a
hyperlink. Multiple hyperlinks can be specified in the text of the control. Each hyperlink can
perform a different task within a application, For example, you can use a hyperlink to display a
Web site in Microsoft Internet Explorer or to load a log file associated with an application.
Each hyperlink displayed in the Linklabel control is an instance of the LinkLabel Link
class. The linklabel. Link class defines display information, state, and location of the hyoperlink.
In addition, the Linkata property of the LinkLabel. Link class enables you to associate
information, such as a URL, to display, with the hyperlink. When a user clicks a hyperlink within
the control, the LinkClicked event is raised, and the LinkLabel. Link object representing the
hyperlink that was clicked is passed as part of the LinkLabelLink Clicked Event Args object that is
passed as a parameter to the event handler. You can use this object to obtain the LinkLabel.
Link object associated with the hyperlink that was clicked by the user. All hyperlink contained
within the LinkLabel control are stored in the LinkLabel. Link Collection class instance for the
control.
There are two ways to add a hyperlink to the Link Label control. The quickest way is to
specify a LinkArea and assign it to the Link Area property. This enables you to specify a single
hyperlink within the text of the control. To add multiple hyperlinks, you can use the Add
method of the LinkLabel.Link Collection class by accessing the collecton through the Links
property.
When a LinkLabel control, a default hyperlik that contains all the text within the
LinkLabel control is added to the LinkLabel. Link Collection. You can override this default link by
specifying a new link area with the Link Aera property, or specify a link using the Addmethod of
the LinkLabel. Link Collection. You can also remove the default hyperlink by using the remove
method of the LinkLabel. Link Collectionclass.
The linkLabel provides a number of properties that enable you to define the display
appearance of hyperlinks in the control. The Active Link Color, Disabled LinkColor, Link Color,
and Visited Link Color properties define the colors used when displaying a hyperlink in various
states. The link Behavior property defines the display of the underline that is associated with a
hyperlink.
Common Dialogs
Visual Basic .NET comes with built-in dialog boxes which allow us to create our own
File Open, File Save, Font, Color dialogs much like what we see in all other windows
applications. To make a dialog box visible at run time we use the dialog box's ShowDialog
method. The Dialog Boxes which come with Visual Basic .NET are: OpenFileDialog,
SaveFileDialog, FontDialog, ColorDialog, PrintDialog, PrintPreviewDialog and
PageSetupDialog. We will be working with OpenFile, SaveFile, Font and Color Dialog's in this
section. The return values of all the above said dialog boxes which will determine
which selection a user makes are: Abort, Cancel, Ignore, No, None, OK, Return, Retry and
Yes.
1.Open file dialog box 2.Save file dialog Box 3.Font dialog box
The Windows Forms OpenFileDialog component is a pre-configured dialog box. It is the same
Open File dialog box exposed by the Windows operating system. It inherits from the
CommonDialog class.
The general concepts of the OpenFileDialog component, which allows you to display a pre-
configured dialog box that users can use to open files. Use this component within your Windows
application as a simple solution for file selection in lieu of configuring your own dialog box. By
relying on standard Windows dialog boxes, you create applications whose basic functionality is
immediately familiar to users
Use the ShowDialog method to display the dialog at run time. You can enable users to multi-
select files to be opened with the Multiselect property. Additionally, you can use the
ShowReadOnly property to determine if a read-only check box appears in the dialog box. The
ReadOnlyChecked property indicates whether the read-only check box is selected. Finally, the
Filter property sets the current file name filter string, which determines the choices that appear in
the "Files of type" box in the dialog box.
Some Basic Properties
1. AddExtension = Gets or sets a value indicating whether the dialog box automatically adds an
extension to a file name if the user omits the extension.
AddExtension As Boolean
2. DefaultExt= The default file name extension. The returned string does not include the period (.). The
default value is an empty string("").
DefaultExt As String
3. FileName = Gets or sets a string containing the file name selected in the file dialog box. A string
containing the file name selected in the file dialog box. The default value is an empty string ("").
FileName As String
4. FileNames Gets the file names of all selected files in the dialog box. An array of values containing the
file names of all selected files in the dialog box.
FileNames As String ()
5.Filter Property Gets or sets the current file name filter string, which determines the
choices that appear in the "Save as file type" or "Files of type" box in the dialog box.
Filter As String
A string that contains information about the file filtering options available in the dialog box.
For each filtering option, the filter string contains a description of the filter, followed by the vertical bar
(|) and the filter pattern. The strings for different filtering options are separated by the vertical bar.
The following is an example of a filter string: "Text files (*.txt)|*.txt|All files (*.*)|*.*"
You can add serveral filter patterns to a filter by separating the file types with smicolons. For example:
"Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"
6. FilterIndex Property. Gets or sets the index of the filter currently selected in the file dialog box.
FilterIndex As Integer
A value containing the index of the filter currently selected in the file dialog box. The first filter is at
index one. The default value is one.
7. Initial Directory Property. Gets or sets the initial directory displayed by the file dialog box.
InitialDirectory As String
A string containing the initial directory displayed by the file dialog box. The default is an empty string
("").
8. Multiselect Property . True if the dialog box allows multiple files to be selected together or
concurrently; otherwise, false. The default value is false.
Multiselect As Boolean
9. ShowHelp . Gets or sets a value indicating whether the Help button is displayed in the file dialog.
ShowHelp As Boolean
10. Title Property . A string containing the file dialog box title. The default value is an empty string ("").
Title As String
Common Methods
1. OpenFile Method . The OpenFile method is used to provide a facility to quickly open a
file from the dialog box. The file is opened in read-only mode for security purposes.
2. ShowDialog Method. Runs a common dialog box with a default owner.
DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel
Common Events
1. FileOk Event . Occurs when the user clicks on the Open or Save button on a file dialog box.
2. HelpRequest Event Occurs when the user clicks the Help button on a common dialog box.
2. SaveFileDialog Component
The Windows Forms SaveFileDialog component is a pre-configured dialog box. It is the same as
the standard Save File dialog box used by Windows. It inherits from the CommonDialog class.
Use it as a simple solution for enabling users to save files in lieu of configuring your own dialog
box. By relying on standard Windows dialog boxes, the basic functionality of applications you
create is immediately familiar to users. You can use the ShowDialog method to display the
dialog box at run time. You can open a file in read-write mode using the OpenFile method.
When it is added to a form, the SaveFileDialog component appears in the tray at the bottom of
the Windows Forms Designer.
Common Methods
1. OpenFile Method . The OpenFile method is used to provide a facility to quickly open a file from
the dialog box. The file is opened in read-only mode for security purposes.
2. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK if the
user clicks OK in the dialog box; otherwise, DialogResult.Cancel .
3. Reset Method Resets all properties to their default values.
Common Events
1. FileOk Event . Occurs when the user clicks on the Open or Save button on a file dialog
box.
2. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.
By default, the dialog box shows list boxes for Font, Font style, and Size; check boxes for effects
like Strikeout and Underline; a drop-down list for Script; and a sample of how the font will
appear. (Script refers to different character scripts that are available for a given font, for example
Hebrew or Japanese.) To display the font dialog box, call the ShowDialog method.
The component has a number of properties that configure its appearance. The properties that set
the dialog-box selections are Font and Color. The Font property sets the font, style, size, script,
and effects; for example, Arial, 10pt, style=Italic, Strikeout.
Basic Property
1. Color Property Gets or sets the selected font color. The color of the selected font. The
default value is Black.
3. MaxSize Property . Gets or sets the maximum point size a user can select.
The maximum point size a user can select. The default is zero.In order for the maximum and
minimum size settings to take effect, MaxSize must be greater than MinSize, and both must be
greater than zero.
4. MinSize Property. Gets or sets the minimum point size a user can select. The minimum point size a
user can select.
5. ShowApply Property . Gets or sets a value indicating whether the dialog box contains an Apply
button. True if the dialog box contains an Apply button; otherwise, false. The default value is
false.
6.ShowColor Property Gets or sets a value indicating whether the dialog box displays the
color choice.True if the dialog box displays the color choice; otherwise, false. The default value
is false.
7. Show Effects Sets a value indicating whether the dialog box contains controls that allow the
user to specify strikethrough, underline, and text color options.
8. Show Apply. Sets a value indicating whether the dialog box contains an Apply button.
9. Show Help. Sets a value indicating whether the dialog box displays a Help button.
Common Methods
3. Apply Event . Occurs when the user clicks the Apply button in the font dialog box.
4. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.
Basic Properties
1. Allow Full Open Gets or sets a value indicating whether the user can use the dialog box to define
custom colors.
2. Any Color Gets or sets a value indicating whether the dialog box displays all available colors in the set
of basic colors.
3. Color Gets or sets the color selected by the user.
4.CustomColors Gets or sets the set of custom colors shown in the dialog box.
5. Full Open Gets or sets a value indicating whether the controls used to create custom colors are visible
when the dialog box is opened
6. Show Help Gets or sets a value indicating whether a Help button appears in the color dialog box.
7.SolidColorOnly . Gets or sets a value indicating whether the dialog box will restrict users to selecting
solid colors only.
Common Methods
1. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK
if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel .
2. Reset Method resets all properties to their default values.
Common Events
1. HelpRequest Event Occurs when the user clicks the Help button on a common dialog
box.
5. Print Dialog Control. The Windows Forms Print Dialog component is a pre-configured
dialog box used to select a printer, choose the pages to print, and determine other print-related
settings in Windows applications. Use it as a simple solution for printer and print-related settings
selection in lieu of configuring your own dialog box. You can enable users to print many parts of
their documents: print all, print a specified page range, or print a selection. By relying on
standard Windows dialog boxes, you create applications whose basic functionality is
immediately familiar to users
Basic Properties
1. Allow PrintToFile Gets or sets a value indicating whether the Print to file check box is
enabled.
2. AllowSelection Gets or sets a value indicating whether the From... To... Page option
button is enabled.
3. AllowSomePages Gets or sets a value indicating whether the Pages option button is
enabled.\
4. Document Gets or sets a value indicating the PrintDocument used to obtain
PrinterSettings.
5. PrinterSettings Gets or sets the PrinterSettings the dialog box modifies.
6. PrintToFile Gets or sets a value indicating whether the Print to file check box is checked.
7. ShowHelp Gets or sets a value indicating whether the Help button is displayed.
8. ShowNetwork Gets or sets a value indicating whether the Network button is displayed.
Common Methods
1. ShowDialog Method. Runs a common dialog box with a default owner. DialogResult.OK if the
user clicks OK in the dialog box; otherwise, DialogResult.Cancel .
Common Events
2. HelpRequest Event Occurs when the user clicks the Help button on a
common dialog box.
Example:
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
RichTextBox1.Text = " "
End Sub
The second form you've just created is called a Modeless form. These are
forms than can be hidden or sent to the taskbar. You can then return to the
main form or programme and do things with it.
A Modal form is sometimes called a dialogue box. And we'll see how to create
one of these now.
Add a second button to your Form1. Change the Name property of the new
button to btnDialogueBox. Double click the new button and add the following
code:
frmDialogue.ShowDialog()
To display a form as a Modal dialogue box, you use the ShowDialog method.
If you use the Show method, the form is displayed as a Modeless form.
Run your programme. Click your new button, and the second form should
display. Move it out the way and try to click a button on Form1. You won't be
able to. The second form has to be dealt with before you can access Form1.
When the form is a Modal dialogue box, you can create OK and Cancel
buttons for it. VB.NET then has a trick up its sleeve for these types of buttons.
We'll see that trick now.
After defining the structure of your form with the WinForms designer you
can display your forms in code with two different methods.
Menus
Every windows user is familiar with menus you wouldn’t get far in
windows without them. Menu are those controls that allow the user to make
selections and also hide away those selection when they are not needed
saving space in windows applications.
Menu items
Menu like file or edit and the actual items in such menus or supported with the
menus items class. This class supports the actual control in your menus systems , and
its their click event that you code to in order to make that menu system active.
You can use the shortcut properties to define a keyboard combination(like
Ctrl+X) that can be pressed to select the menu item ,set the show shortcut property to
true to display that key combination in the menu items caption. To set the caption of a
menu items you use the text property . setting the text to a hyphen(-) converts the menu
items into a menu separator, one of those horizontal bars that help group together. You
can even have separator in mean the bars , In & underlines that character and makes it
into an access key, which mean the use the user can select that item by pressing alt
and that character. For example giving a menu items the caption “E&xit” makes x in to
the access key for these menu items .you can enable and disable menu items with the
enable property and so or hide then with the visible property. Note that for menu items
to be display you have to add it to a main menu (or context menu) Object.
Context Menu :
Another popular type of menus is context menus .you use context menu
controls to give users access to frequently used menu commands, and bring them up
by right clicking another control . You can see context menus to display control specific
options , such as cut ,copy and paste in textboxes.
You associate context menus with other control by setting the control’s context
menu property to context menu control. the central property of the context menu control
is the menu items property , you can add menu items to a context menu at design time
or in code by creating menu items object and adding then to the menu items collections
of the context menu . as with main menus , context menu items can be disable , hidden,
or deleted . you also can show context menus yourself with the context menu controls
show method. They hide away as soon as you click some where other then on them .
you can handle the menu items click , select and popup event as you can in main
menus . if fact the only major difference here is that context menu are not divided in to
separate menus like file ,edit ,window and so on.
ToolTip
The Windows Forms ToolTip component displays text when the user points at controls.
A ToolTip can be associated with any control. An example use of this control: In order to
save space on a form, you can display a small icon on a button and use a ToolTip to
explain the button's function.
Working with the ToolTip Component
A ToolTip component provides a ToolTip property to multiple controls on a Windows Form or
other container. For example, if you place one ToolTip component on a form, you can display
"Type your name here" for a TextBox control and "Click here to save changes" for
a Button control.
The key methods of the ToolTip component are SetToolTip and GetToolTip. You can use
the SetToolTip method to set the ToolTips displayed for controls.
MDI Form
MDI stands for Multiple Document Interface applications that allow users to work with
multiple documents by opening more than one document at a time. Whereas, a Single Document
Interface (SDI) application can manipulate only one document at a time.
The MDI applications act as the parent and child relationship in a form. A parent form is
a container that contains child forms, while child forms can be multiple to display different
modules in a parent form.
1. MidParent: The MidParent property is used to set a parent form to a child form.
2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the
current child form.
4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent
or main form.
5. Controls: It is used to get the reference of control from the child form.
MDI (Multiple Document Interface) Application is an application in which we can view and
work with several documents at once. Example of an MDI application is Microsoft Excel.
Excel allows us to work with several documents at once. In contrast, SDI (Single Document
Interface)
applicatio
ns are the
applicatio
ns which
allows us
to work
with a
single
document
at once.
Example
of a single
document
applicatio
n is
Microsoft Word in which only one document is visible at a time. Visual Basic .NET provides
great support for creating and working with MDI applications. In general, MDI applications
are mostly used by financial services organizations where the user needs to work with
several documents at once.
With this application a new child window is displayed each time the New Child
Window menu item is clicked, all child windows will be arranged when you click
Arrange Child Windows menu item. To get the desired result, open the code
designer window and paste the following code.
When you run the application and click "New Child Window" menu item, a new child
window is displayed. Five child windows will be displayed as we declared an array of five
in code. The image below displays the output.
When you click on "Arrange Child Windows" menu item, all child windows are arranged. It
looks like the image below.
To make the MDI container form, make a form and set its IsMdiContainer property to True.
To make a menu list the MDI child forms, set its MdiList property to True.
Use code similar to the following to add a MDI child form to the MDI container.
When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that
is, what an object of the class will consist of and what operations can be
performed on such an object.
Objects are instances of a class. The methods and variables that constitute a
class are called members of the class.
Class Definition
A class definition starts with the keyword Class followed by the class name;
and the class body, ended by the End Class statement. Following is the
general form of a class definition −
Class name
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
Inherits specifies the base class it is inheriting from.
Implements specifies the interfaces the class is inheriting from.
The following example demonstrates a Box class, with three data members,
length, breadth and height −
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Volume of Box1 : 210
Volume of Box2 : 1560
We can define class members as static using the Shared keyword. When we
declare a member of a class as Shared, it means no matter how many objects
of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists for a
class. Shared variables are used for defining constants because their values
can be retrieved by invoking the class without creating an instance of it.
Shared variables can be initialized outside the member function or class
definition. You can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can
access only Shared variables. The Shared functions exist even before the
object is created.
The following example demonstrates the use of shared members −
Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Value of variable num: 3
Inheritance
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class
which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast
implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.
A class can be derived from more than one class or interface, which means
that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Total area: 35
The derived class inherits the base class member variables and member
methods. Therefore, the super class object should be created before the
subclass is created. The super class or the base class is implicitly known
as MyBase in VB.Net
The following program demonstrates this −
' Base class
Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5