unit iv advanced features of vb - … · does not exist. defaultext gets or sets the default file...

81
UNIT IV ADVANCED FEATURES OF VB.NET

Upload: hadien

Post on 20-Apr-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

UNIT – IV

ADVANCED FEATURES OF

VB.NET

SYLLABUS

4.1 Dialog Boxes

4.1.1 Open File Dialog

4.1.2 Save File Dialog

4.1.3 Font Dialog

4.1.4 Color Dialog

4.1.5 Print Dialog

4.2 Sub Routine and Function

4.2.1 Sub Routine

4.2.2 Function

4.2.3 Pass by value and pass by reference

2

SYLLABUS

4.3 Exception Handling

4.3.1 What is error?

4.3.2 Categories of error

4.3.3 Categories of exception handling

4.3.3.1 Structure exception handling

4.3.3.2 Try…Catch ….Finally

4.3.3.3 Common exception handling

4.3.3.4 Message property and to string method

3

CONT…

4.3.3.5 Throw

4.3.4 Unstructured exception handling

4.3.3.1 On error statement

4.3.3.2 Err object

4.3.3.3 Resume Next

4.4 SDI/MDI

4

4.1DIALOG BOXES

There are many built-in dialog boxes to be used in

Windows forms for various tasks like opening and

saving files, printing a page, providing choices for

colors, fonts, page setup, etc., to the user of an

application.

The ShowDialog method is used to display all thedialog box controls at run-time.

5

CONT…

6

4.1.1 OPEN FILE DIALOG

It prompts the user to open a file and allows the

user to select a file to open.

The user can check if the file exists and then open

it.

7

CONT…

Property Description

AddExtension

Gets or sets a value indicating whether the dialog box

automatically adds an extension to a file name if the user

omits the extension.

CheckFileExists

Gets or sets a value indicating whether the dialog box

displays a warning if the user specifies a file name that

does not exist.

DefaultExt Gets or sets the default file name extension.

FileNameGets or sets a string containing the file name selected in

the file dialog box.

Filter

Gets or sets the current file name filter string, which

determines the choices that appear in the "Save as file

type" or "Files of type" box in the dialog box.

InitialDirectoryGets or sets the initial directory displayed by the file

dialog box.

MultiselectGets or sets a value indicating whether the dialog box

allows multiple files to be selected.

8

CONT…

Method Name Description

OpenFile

Opens the file selected by the user, with read-only

permission. The file is specified by the FileName

property.

Reset Resets all options to their default value.

9

EXAMPLE

Private Sub Button1_Click(sender As Object, e As EventArgs)

Handles Button1.Click

If OpenFileDialog1.ShowDialog < >

Windows.Forms.DialogResult.Cancel Then

PictureBox1.Image =

Image.FromFile(OpenFileDialog1.FileName)

End If

End Sub

10

CONT…

11

4.1.2 SAVE FILE DIALOG

The Save File Dialog control prompts the user to

select a location for saving a file and allows the user to

specify the name of the file to save data.

12

CONT…

Property Description

AddExtension

Gets or sets a value indicating whether the dialog box

automatically adds an extension to a file name if the

user omits the extension.

CheckFileExists

Gets or sets a value indicating whether the dialog box

displays a warning if the user specifies a file name that

does not exist.

CheckPathExists

Gets or sets a value indicating whether the dialog box

displays a warning if the user specifies a path that does

not exist.

DefaultExt Gets or sets the default file name extension.

FileNameGets or sets a string containing the file name selected in

the file dialog box.

InitialDirectoryGets or sets the initial directory displayed by the file

dialog box.

OverwritePrompt Gets or sets a value indicating whether the Save As

dialog box displays a warning if the user specifies a file

name that already exists.

13

CONT…

Method Name Description

Open File Opens the file with read/write permission.

Reset Resets all dialog box options to their default values..

14

EXAMPLE

Private Sub Button1_Click(sender As Object, e As EventArgs)

Handles Button1.Click

SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"

If SaveFileDialog1.ShowDialog =

Windows.Forms.DialogResult.OK Then

My.Computer.FileSystem.WriteAllText(SaveFileDialog

1.FileName, RichTextBox1.Text, True)

End If

End Sub

15

CONT…

16

4.1.3 FONTDIALOG

It prompts the user to choose a font from among those

installed on the local computer and lets the user

select the font, font size, and color.

It returns the Font and Color objects.

17

CONT…

Property Description

Color Gets or sets the selected font color.

AllowVerticalFonts

Gets or sets a value indicating whether the dialog box

displays both vertical and horizontal fonts, or only

horizontal fonts.

Font Gets or sets the selected font.

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

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

ShowColorGets or sets a value indicating whether the dialog box

displays the color choice.

ShowEffects

Gets or sets a value indicating whether the dialog box

contains controls that allow the user to specify

strikethrough, underline, and text color options.

ShowApplyGets or sets a value indicating whether the dialog box

contains an Apply button18

CONT…

Method Name Description

Reset Resets all options to their default values.

RunDialogWhen overridden in a derived class, specifies a

common dialog box.

ShowDialog Runs a common dialog box with a default owner.

19

EVENTS OF THE FONTDIALOG CONTROL

Event Name Description

ApplyOccurs when the Apply button on the font dialog

box is clicked.

EXAMPLE

Private Sub Button1_Click(sender As Object, e As

EventArgs) Handles Button1.Click

If FontDialog1.ShowDialog <>

Windows.Forms.DialogResult.Cancel Then

RichTextBox1.ForeColor = FontDialog1.Color

RichTextBox1.Font = FontDialog1.Font

End If

End Sub

20

CONT…

21

4.1.4 COLOR DIALOG

The Color Dialog control class represents a common

dialog box that displays available colors along with

controls that enable the user to define custom colors.

It lets the user select a color.

22

CONT…

Property Description

AllowFullOpenGets or sets a value indicating whether the user can

use the dialog box to define custom colors.

AnyColorGets or sets a value indicating whether the dialog box

displays all available colors in the set of basic colors.

Color Gets or sets the color selected by the user.

CustomColorsGets or sets the set of custom colors shown in the

dialog box.

FullOpen

Gets or sets a value indicating whether the controls

used to create custom colors are visible when the dialog

box is opened

SolidColorOnlyGets or sets a value indicating whether the dialog box

will restrict users to selecting solid colors only.

23

CONT…

Method Name Description

Reset

Resets all options to their default values, the last

selected color to black, and the custom colors to

their default values.

RunDialogWhen overridden in a derived class, specifies a

common dialog box.

ShowDialog Runs a common dialog box with a default owner.

24

EXAMPLE

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

Button1.Click

If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then

Label1.ForeColor = ColorDialog1.Color

End If

End Sub

25

4.1.5 PRINT DIALOG

The Print Dialog control lets the user to print

documents by selecting a printer and choosing which

sections of the document to print from a Windows

Forms application.

26

CONT…

27

CONT…

Property Description

AllowCurrentPageGets or sets a value indicating whether

the Current Page option button is displayed.

AllowPrintToFileGets or sets a value indicating whether the Print

to file check box is enabled.

AllowSelectionGets or sets a value indicating whether

the Selectionoption button is enabled.

AllowSomePagesGets or sets a value indicating whether

the Pagesoption button is enabled.

PrintToFile Gets or sets a value indicating whether the Print

to file check box is selected.

PrinterSettings Gets or sets the printer settings the dialog box

modifies. 28

METHODS OF THE PRINT DIALOG CONTROL

Method Name Description

Reset Resets all options to their default values.

RunDialogWhen overridden in a derived class, specifies a

common dialog box.

ShowDialog Runs a common dialog box with a default owner.

29

EXAMPLE

Private Sub Button1_Click(sender As Object, e As EventArgs)

Handles Button1.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

30

CONT…

31

4.2 SUB PROCEDURE & FUNCTIONS

A procedure is a group of logically related statements

that is used to perform a specific task.

Using procedure, large application can be divided into

smaller units.

Types of Procedure

Sub Procedure

Function Procedure

Pass by value and Pass by reference

32

4.1.1 SUB PROCEDURES

They're the handy blocks of code that can organize

your code into single-purpose sections to make

programming easier.

Unlike functions, Sub procedures do not return values,

but like functions.

We can pass values to Sub procedures in an argument

list.

33

CONT…

A general procedure is a group of logically relatedstatements that are used to perform a specific task.

It is also known as sub procedure.

We can pass arguments to the sub procedure.

Sub procedure does not return any value.

An Event procedure is invoked automatically when userinteracts with particular control.

Sub procedure does not invoke automatically. Subprocedure is called explicitly.

Calling of Sub Procedure

Call ProcedureName ([Argument List])

ProcedureName [Argument List] 34

CONT…

Syntax:

[Scope] Sub ProcedureName ([Argument List])

procedure statements

End Sub

Scope:

It is optional.

It can be either Public, Private or Protected scope.

Default is Public.

Procedure Name:

• It specify the name of procedure

Argument List:

It is optional.35

CONT…

Example:

Sub MaximumNo (ByVal a As Integer, ByVal b As

Integer)

If a > b Then

MsgBox (“ A is Maximum Number”)

Else

MsgBox (“ B is Maximum Number”)

End if

End Sub

36

CONT…

Calling of Above Function

Call MaximumNo(txtNo1.Text, txtNo2.Text)

or

MaximumNo(txtNo1.Text, txtNo2.Text)

37

4.2.2 FUNCTION PROCEDURE

A Function procedure is a group of logically related

statements that are used to perform a specific task.

We can pass arguments to the function procedure.

A function procedure can return a value.

A sub procedure can not return a value while a

function procedure can return a value.

Function procedure can be defined using Function

and End Function keywords.

Calling of Function Procedure

Call FunctionName ([Argument List])

FunctionName [Argument List] 38

CONT…

Syntax:

[Scope] Function FunctionName ([Argument List])[As ReturnType]

Function statements

[Return Statements]

End Function

Scope:

It is optional.

It can be either Public, Private or Protected scope.

Default is Public.

Function Name:

• It specify the name of function procedure.39

CONT…

Return Type:

It is optional. If function procedure returnsany value then user has to specify returntype.

Argument List:

It is optional.

40

CONT…

Example:

Function MaximumNo (ByVal a As Integer, ByVal b AsInteger)

If a > b Then

Return a

Else

Return b

End if

End Function

Calling of Above Function

txtMax.Text = MaximumNo(txtNo1.Text, txtNo2.Text)

41

4.2.3 PASSING PARAMETERS BY VALUE

This is the default mechanism for passing parameters

to a method.

In this mechanism, when a method is called, a new

storage location is created for each value parameter.

The values of the actual parameters are copied into

them.

So, the changes made to the parameter inside the

method have no effect on the argument.

In VB.Net, you declare the reference parameters using

the ByVal keyword.

42

Module paramByval

Sub swap(ByVal x As Integer, ByVal y As Integer)

Dim temp As Integer

temp = x

x = y

y = temp

End Sub

Sub Main()

Dim a As Integer = 100

Dim b As Integer = 200

Console.WriteLine("Before swap, value of a : {0}", a) Console.WriteLine("Before swap, value of b : {0}", b)

swap(a, b)

Console.WriteLine("After swap, value of a : {0}", a) Console.WriteLine("After swap, value of b : {0}", b) Console.ReadLine()

End Sub

End Module 43

CONT…

Output:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :100

After swap, value of b :200

44

CONT…

PASSING PARAMETERS BY REFERENCE

A reference parameter is a reference to a memory

location of a variable.

When you pass parameters by reference, unlike value

parameters, a new storage location is not created for

these parameters.

The reference parameters represent the same memory

location as the actual parameters that are supplied to

the method.

In VB.Net, you declare the reference parameters using

the ByRef keyword.

45

Module paramByref

Sub swap(ByRef x As Integer, ByRef y As Integer)

Dim temp As Integer

temp = x

x = y

y = temp

End Sub

Sub Main()

Dim a As Integer = 100

Dim b As Integer = 200

Console.WriteLine("Before swap, value of a : {0}", a)

Console.WriteLine("Before swap, value of b : {0}", b) 46

EXAMPLE:

CONT…

swap(a, b)

Console.WriteLine("After swap, value of a : {0}",

a) Console.WriteLine("After swap, value of b :

{0}", b) Console.ReadLine()

End Sub

End Module

47

Output:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

48

CONT…

4.3 EXCEPTION HANDLING

4.3.1 What is error?

An exception is a problem that arises during the

execution of a program. An exception is a

response to an exceptional circumstance that

arises while a program is running, such as an

attempt to divide by zero.

Exceptions provide a way to transfer control from

one part of a program to another.VB.Net

exception handling is built upon four keywords:

Try, Catch, Finally and Throw.

49

4.3.2 CATEGORIES OF ERRORS

1.Syntax error

2.Logical error

3.Runtime error

50

CONT…

1. Syntax error

Syntax Errors. ... Visual Basic checks your code

as you type it in the Code Editor window and

alerts you if you make a mistake, such as

misspelling a word or using a language element

improperly.

Syntax errors are the most common type

of errors. You can fix them easily in the coding

environment as soon as they occur

51

CONT…

2.Logical error

In computer programming, a logic error is

a bug in a program that causes it to operate

incorrectly, but not to terminate abnormally (or

crash).

A logic error produces unintended or undesired

output or other behavior, although it may not

immediately be recognized as such.

52

EXAMPLE

Dim x As Integer

Dim y As Integer

Dim answer As Integer

x = 10.5

y = 3

answer = x * y

TextBox1.Text = answer

When you've added the code to your button, run

your program and test it out.

You'd think that 10.5 multiplied by 3 would give

you the answer 31.5. Click your button. The

answer that appears in your textbox is 30! 53

4.3.3 CATEGORIES OF EXCEPTION HANDLING

.NET provides two types of Exception Handling

1.Structured Error Handling

2.Unstructured Error Handling

1) On Error Goto Line

2) On Error Resume Next

3) On Error Goto 0 or -1

4) Err Object

54

Structured Error Handling can be managed using

Try…Catch…Finally structure in VB.NET.

Syntax:

Try

[ tryStatements ]

[ Exit Try ]

[ Catch [ exception [ As type ] ]

[ When expression ] [ catchStatements ]

[ Exit Try ] ]

[ Catch ... ]

[ Finally

m,.[ finallyStatements ] ]

End Try55

1.STRUCTURED ERROR HANDLING

4.3.3.1 EXCEPTION HANDLING

An exception is a problem that arises during the

execution of a program.

An exception is a response to an exceptional

circumstance that arises while a program is running,

such as an attempt to divide by zero.

Whenever an Exception is encountered the application

is crashed and its execution is terminated.

56

CONT…

57

4.3.3.2

1) Try

it contains that you want to execute.

It is optional Try statement block may contain one or more statements.

2) Catch

The exception that is thrown from Try block is caught by catch block.

Catch block contains code that handles the Exception.

3) Finally

It contains statements that must execute before exit from the Try….catch …block 58

CONT…

Example:

Try [ try Statements ]

[ Exit Try ]

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

[ catch Statements ]

[ Exit Try ] ]

[ Catch ... ]

[ Finally [ finally Statements ] ]

End Try

59

4.3.3.3 COMMON EXCEPTION CLASS

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRange

Exception

Handles errors

generated when a

method refers to an

array index out of

range.

System.ArrayTypeMismat

chException

Handles errors

generated when type is

mismatched with the

array type.60

4.3.3.4 MESSAGE PROPERTY AND TO

STRING METHOD

Message Property

using try..catch for error handling and getting

the message displayed as:

Message box. show (ex. to string)

But it gives very long message.

Is it possible just to get only the actual error or

could give my own modified message.

61

CONT…

To String method

To String is often useful in VB.NET programs. It

allows us to provide a custom To String function

on a VB.NET class.

By using an Overrides To String function, we

specify how an instance renders itself as a String.

62

EXAMPLE:

Public Overrides Function To String() As String

Return String. Format("[{0}, {1}]", _a, _b)

End Function

End Class

Sub Main()

Dim p As Perl = New Perl(2, 3)

Console.WriteLine(p)

End Sub

End Module

Output [2, 3]63

4.3.3.5 THROW

Throwing Objects

You can throw an object if it is either directly or

indirectly derived from the System. Exception

class.

You can use a throw statement in the catch block

to throw the present object as:

Throw

[ expression ]

64

EXAMPLE

Module exceptionProg

Sub Main()

Try

Throw New ApplicationException("A custom exception _

is being thrown here...")

Catch e As Exception

Console.WriteLine(e.Message)

Finally

Console.WriteLine("Now inside the Finally Block")

End Try

Console.ReadKey()

End Sub

End Module65

2.UNSTRUCTURED ERROR HANDLING

Unstructured Error Handling

1) On Error Goto Line

2) On Error Resume Next

3) On Error Goto 0 or -1

4) Err Object

1) On Error Goto Line

On Error Goto Line statement is used to turnON the error trapping facility.

Syntax:On error goto line

Here Line indicate any valid label Name. 66

4.3.4.1

On Error statement

Once an error is handled by an error handler in

any procedure, execution resumes in the current

procedure at the point designated by

the Resume statement.

An error-handling routine is not a Sub

procedure or a Function procedure. It is a section

of code marked by a line label or a line number.

67

EXAMPLE:

68

4.3.4.2 Err Object

Err object is the in built object supported by

vb.net.

Err object contains information abut run time

errors encountered during execution of

application.

Err object has several properties ans methods

like Number, Description, Erl,

clear(),raise() etc.

69

4.3.4.3 RESUME NEXT

2) On Error Goto 0 and -1

On Error Goto 0 and -1 statement is used

to disable the error trapping mechanism.

It is used to turned ON and OFF of error

trapping mechanism.

3)On Error Resume Next

Specifies that when an exception occurs,

execution skips over the Statement that

caused the problem and goes to the

statement immediately following.

Execution continues from that point.70

2.UNSTRUCTURED ERROR HANDLING

4) Err Object

Err object is the in built object supported byvb.net.

Err object contains information abut runtime errors encountered during execution ofapplication.

Err object has several properties ansmethods like Number, Description, Erl,clear(),raise() etc.

71

EXAMPLE OF THE UNSTRUCTURED ERROR

HANDLING

Public Class Form1

Private Sub btnDivison_Click(ByVal sender As

System.Object, ByVal e As System.EventArgs)

Handles

btnDivison.Click

Dim int1, int2, ans As Integer

int1 = Num1txt.Text

int2 = Num2txt.Text

On Error GoTo Handle 'Global

Error Handling

ans = int1 \int 272

“On Error GoTo 0 ' If any error is there which is in this

particular statement then at that

time we can use this statement”

“On Error GoTo -1 'It ignore the particular type of

exception.”

anstxt.Text = ans

Num1txt.Text = ""

Num2txt.Text = ""

Handle:73

EXAMPLE OF THE UNSTRUCTURED ERROR

HANDLING

If (TypeOf Err.GetException() Is DivideByZeroException)

Then

MsgBox("Error Caught..!!")

Resume Next

End If

End Sub

End Class

74

EXAMPLE OF THE UNSTRUCTURED ERROR

HANDLING

4.4 SDI/MDI

1. Create a Windows Application.

2. In the Properties window, set

the IsMDIContainer property to true.

3. From the Toolbox, drag

a MainMenu component to the form. Create a

top-level menu item with the Text property set

to &File with submenu items

called &New and &Close. Also create a top-

level menu item called &Window.75

TO CREATE AN MDI PARENT FORM AT

DESIGN TIME

The first menu will create, and hide menu items

at run time, and the second menu will keep

track of the open MDI child windows. At this

point, you have created an MDI parent window.

For more information on creating menus and

menu items

4. Press F5 to run the application. For information

about creating MDI child windows that operate

within the MDI parent form

76

CREATING MDI CHILD FORMS

1.Create an MDI parent form that has a menu structure containing File and Window top-level menu items and New and Close menu items. For more information on creating MDI parent forms.

2. In the drop-down list at the top of the Properties window, select the menu item that corresponds to the &Window menu item and set the MdiList property to true.

This will enable the Window menu to maintain a list of open MDI child windows with a check mark next to the active child window.

77

CREATING MDI CHILD FORMS

3. In Solution Explorer, right-click the project, point to Add, and then select Add New Item.

This form will be the template for your MDI child forms.

Note : The MDI child form you create in this step is a standard Windows Form. As such, it has an Opacity property, which allows you to control the transparency of the form. However, the Opacity property was designed for top-level windows. Do not use it with MDI child forms, as painting problems can occur. 78

CREATING MDI CHILD FORMS

4. In the Add New Item dialog box, select Windows Form (in Visual Basic or in Visual C#) or Windows Forms Application (.NET) (in Visual C++) from the Templates pane. In the Name box, name the form Form2. Click the Open button to add the form to the project.

The Windows Forms Designer opens, displaying Form2.

5. Drag a RichTextBox control from the Toolbox to the form.

6. In the Properties window, set the Anchor property to Top, Left and the Dock property to fill.

79

CREATING MDI CHILD FORMS

This causes the RichTextBox control to

completely fill the area of the MDI child

form, even when the form is resized.

7. Create a Click event handler for the new menu

item. For more information about creating event

handlers.

8.Insert code similar to the following to create a

new MDI child form when the user clicks

the New menu item

80

MDI VS. SDI

MDI SDI

MDI stand for Multiple Document Interface

SDI stand for Single Document Interface.

In MDI you can work with more then one form in the same workspace.

In SDI you can not work with more then one form in the same workspace.

In MDI application there is a relationship between MDI and SDI forms which is known as parent child relationship.

In SDI there is no relationship between SDI forms.

It is best for the application that contains more than one forms.Example: Microsoft World

It is best for the application that contains only single form.

Example: Microsoft Note Pad.81