visual basic message box

Upload: jenny-bautista

Post on 02-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Visual Basic Message Box

    1/11

    The MsgBox Function and the MessageBox Class

    The message box dialog is one of the most common ways to display custom messages to the user andaccept their input regarding the choice that they have made. VB.NET provides two ways to use messageboxes: the first is theMsgBoxfunction, which is part of the Microsoft.VisualBasic namespace and iscoded in a fashion very similar to pre-.NET versions of VB; the second is the MessageBoxclass, whichhas a slightly different syntax, and is the native .NET way to use message boxes. Both methodologies arepresented below.

    The MsgBox Function

    The MsgBoxfunction displays a message in a dialog box, waits for the user to click a button, and returnsan Integer indicating which button the user clicked.

    Syntax:MsgBox(prompt[, buttons] [, title])

    - or IntegerVariable= MsgBox(prompt[, buttons] [, title])

    The MsgBoxfunction syntax has these parts:

    Part Description

    prompt Required. String expression displayed as the message in the dialog box. The maximumlength of prompt is approximately 1024 characters, depending on the width of thecharacters used.

    but tons Optional. Numeric expression that is the sum of values specifying the number and typeof buttons to display, the icon style to use, the identity of the default button, and themodality of the message box. If omitted, the default value for but tons is 0 (whichcauses only an OK button to be displayed with no icon). The buttons argument isexplained in more detail below.

    t i t le Optional. String expression displayed in the title bar of the dialog box. If you omit t i t le ,the application name is placed in the title bar.

    The but tons argument

    The buttons argument is formed by five groups of values. The first group of values (05) describes thenumber and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes theicon style; the third group (0, 256, 512, 768) determines which button is the default; the fourth group (0,4096) determines the modality of the message box; and the fifth group contains values that would only beused under special circumstances. When adding numbers to create a final value forthe but tons argument, use only one number from each group.

    Note: For each value, a corresponding built-in constant (either the classic "vb" constants or the .NET"MsgBoxStyle" enumeration constants) may also be used. Use of the constants is preferred forreadability. The "vb" constants were introduced in earlier versions of Visual Basic and may also be usedin VB.NET. VB.NET also provides the "MsgBoxStyle" enumeration constants which can be used as an

    alternative to the "vb" constants.

    First Group:Determines which buttons to display:

    Constant Value Description

    vbOKOnly- or -

    MsgBoxStyle.OKOnly

    0 Display OKbutton only.

  • 8/11/2019 Visual Basic Message Box

    2/11

    vbOKCancel- or -MsgBoxStyle.OKCancel

    1 Display OKand Cancelbuttons.

    vbAbortRetryIgnore- or -MsgBoxStyle.AbortRetryIgnore

    2 Display Abort, Retry, and Ignorebuttons.

    vbYesNoCancel

    - or -MsgBoxStyle.YesNoCancel

    3

    DisplayYes, No, and Cancelbuttons.

    vbYesNo- or -MsgBoxStyle.YesNo

    4 DisplayYesand Nobuttons.

    vbRetryCancel- or -MsgBoxStyle.RetryCancel

    5 Display Retryand Cancelbuttons.

    Second Group:Determines which icon to display:

    Constant

    Value

    Description

    IconvbCritical

    - or -

    MsgBoxStyle.Critical

    16 DisplayCritical Messageicon.

    vbQuestion- or -MsgBoxStyle.Question

    32 Display Warning Query(questionmark) icon.

    vbExclamation- or -MsgBoxStyle.Exclamation

    48 Display Warning Messageicon.

    vbInformation- or -MsgBoxStyle.Information

    64 Display Information Messageicon.

    Third Group:Determines which button is the default:

    Constant Value Description

    vbDefaultButton1- or -MsgBoxStyle.DefaultButton1

    0 First button is default.

    vbDefaultButton2- or -MsgBoxStyle.DefaultButton2

    256 Second button is default.

    vbDefaultButton3- or -

    MsgBoxStyle.DefaultButton3

    512 Third button is default.

    vbDefaultButton4- or -MsgBoxStyle.DefaultButton4

    768 Fourth button is default (applicable only if a Helpbutton has been added).

    Fourth Group:Determines the modality of the message box. Note generally, you would not need to use a constantfrom this group, as you would want to use the default (application modal). If you specified "system modal",

  • 8/11/2019 Visual Basic Message Box

    3/11

    you would be "hogging" Windows i.e., if a user had another app open, like Word or Excel, they wouldnot be able to get back to it until they responded to your app's message box.

    Constant Value Description

    vbApplicationModal- or -

    MsgBoxStyle.ApplicationModal

    0 Application modal; the user must respond to themessage box before continuing work in the

    current application.

    vbSystemModal- or -MsgBoxStyle.SystemModal

    4096 System modal; all applications are suspendeduntil the user responds to the message box.

    Fourth Group:The fifth group of constants that can be used for the buttons argument would only be used under specialcircumstances:

    Constant Value Description

    vbMsgBoxHelpButton- or -MsgBoxStyle.MsgBoxHelpButton

    16384 Adds Help button to the message box

    vbMsgBoxSetForeground- or -

    MsgBoxStyle.MsgBoxSetForeground

    65536

    Specifies the message box window as theforeground window

    vbMsgBoxRight

    - or -MsgBoxStyle.MsgBoxRight

    524288

    Text is right aligned

    vbMsgBoxRtlReading- or -MsgBoxStyle.MsgBoxRtlReading

    1048576 Specifies text should appear as right-to-leftreading on Hebrew and Arabic systems

    When you use MsgBox to with the option to display more than one button (i.e., from the first group,anything other than "vbOKOnly"), you can test which button the user clicked by comparing the returnvalue of the Msgbox function with one of these values.

    Note: For each return value, a corresponding built-in constant (either the classic "vb" constants or the.NET "MsgBoxResult" enumeration constants) may also be used. Use of the constants is preferred forreadability. The "vb" constants were introduced in earlier versions of Visual Basic and may also be usedin VB.NET. VB.NET also provides the "MsgBoxResult" enumeration constants which can be used as analternative to the "vb" constants.

    Constant Value Description

    vbOK-or-MsgBoxResult.OK

    1 The OK button was pressed

    vbCancel-or-

    MsgBoxResult.Cancel

    2 The Cancel button was pressed

    vbAbort-or-MsgBoxResult.Abort

    3 The Abort button was pressed

    vbRetry-or-MsgBoxResult.Retry

    4 The Retry button was pressed

    vbIgnore-or-

    5 The Ignore button was pressed

  • 8/11/2019 Visual Basic Message Box

    4/11

    MsgBoxResult.Ignore

    vbYes-or-MsgBoxResult.Yes

    6 TheYes button was pressed

    vbNo-or-

    MsgBoxResult.No

    7 The Nobutton was pressed

    Note: To try any of the MsgBox examples, you can simply start a new project, double-click on the form,and place the code in the Form_Load event.

    There are two basic ways to use MsgBox, depending on whether or not you need to know which buttonthe user clicked.

    If you do NOT need to test which button the user clicked (i.e., you displayed a message box withonly an OK button), then you can use MsgBox as if you were calling a Sub. You can use thefollowing syntax:

    MsgBox(arguments)

    Examples:

    o The statement

    MsgBox("Hello there!")

    causes the following box to be displayed:

    This is the simplest use of MsgBox: it uses only the requiredprompt argument. Sincethe buttonsargument was omitted, the default (OK button with no icons) was used; andsince the titleargument was omitted, the default title (the project name) was displayed inthe title bar.

    o The statement

    MsgBox("The Last Name field must not be blank.", _vbExclamation, _

    "Last Name")

    causes the following box to be displayed:

  • 8/11/2019 Visual Basic Message Box

    5/11

    This is how a data entry error might be displayed. Note that vbExclamationwas specifiedfor the buttonsargument to specify what icon should be displayed the fact that we didnot add a value from the first group still causes only the OK button to be displayed. If youwanted to explicitly indicate that only the OK button should be displayed along with theexclamation icon, you could have coded the second argument as

    vbExclamation + vbOKOnly

    making the full statement read:

    MsgBox("The Last Name field must not be blank.", _vbExclamation + vbOKOnly, _

    "Last Name")

    Remember, for the buttonsargument, you can add one value from each of the four

    groups.

    An alternative (not recommended) is to use the hard-coded number forthe buttonsargument, as in:

    MsgBox("The Last Name field must not be blank.", 48, "LastName")

    Note also that this example provided a value for the titleargument ("Last Name"), which

    causes that text to be displayed in the box's title bar.

    The format of the MsgBox statement used in this example could also be used for morecritical errors (such as a database problem) by using the vbCritical icon. You may alsowant to use the name of the Sub or Function in which the error occurred for your titleargument.

    Example:

    MsgBox("A bad database error has occurred.", _vbCritical, _

    "UpdateCustomerTable")

    Result:

  • 8/11/2019 Visual Basic Message Box

    6/11

    If you DO need to test which button the user clicked (i.e., you displayed a message box withmore than one button), then you must use MsgBox as a function, using the following syntax:

    IntegerVariable= Msgbox (arguments)

    One of the more common uses of MsgBox is to ask a Yes/No question of the user and performprocessing based on their response, as in the following example:

    Dim intResponse As Integer

    intResponse = MsgBox("Are you sure you want to quit?", _vbYesNo + vbQuestion, _

    "Quit")

    If intResponse = vbYes Then' code to end the app, such as "Me.Close" would go here

    End If

    The following message box would be displayed:

    After the user clicks a button, you would test the return variable (intResponse) for a value ofvbYes or vbNo (6 or 7).

    Note that the use of the built-in constants makes the code more readable. The statement

    intResponse = MsgBox("Are you sure you want to quit?", _vbYesNo + vbQuestion, _"Quit")

    is more readable than

    intResponse = MsgBox("Are you sure you want to quit?", 36,"Quit")

    and

    If intResponse = vbYes Then

    is more readable than

    If intResponse = 6 Then

    In that you can use a function anywhere a variable can be used, you could use the MsgBoxfunction directly in an If statement without using a separate variable to hold the result("intResponse" in this case). For example, the above example could have been coded as:

    If MsgBox("Are you sure you want to quit?", _

  • 8/11/2019 Visual Basic Message Box

    7/11

    vbYesNo + vbQuestion, _

    "Quit")= vbYes Then

    ' code to end the app, such as "Me.Close" would go hereEnd If

    Note: If desired you could place the code for this example in the cmdExit_Click event of any ofthe "Try It" projects.

    Following is an example using the vbDefaultButton2constant:

    Dim intResponse As Integer

    intResponse = MsgBox("Are you sure you want to delete all of therows " _

    & "in the Customer table?", _

    vbYesNo + vbQuestion + vbDefaultButton2, _"Delete")

    If intResponse = vbYes Then

    ' code to delete the rows would go here ...End If

    The message box displayed by this example would look like this:

    The first sample project for this topic contains a command button for each MsgBox example given above.

  • 8/11/2019 Visual Basic Message Box

    8/11

    Download the VB.NET project code for the example abovehere.

    The MessageBox Class

    As an alternative, .NET has introduced a class called MessageBox which encapsulates all the features ofMsgBox. The difference between MsgBox and MessageBox is that Msgbox is a function whileMessageBox is a class. The MessageBox class has various overloaded Showmethods for differentparameters. From a practical standpoint, both the MsgBox function and the MessageBox class willaccomplish the same thing. You will notice that the arguments for MessageBox are specified in a slightlydifferent order from MsgBox.

    MessageBox.Show Method

    To show the message box we need to call the Show method of the MessageBox class, for example:

    MessageBox.Show("Hello World!")

    As mentioned earlier, the Show method has various overloaded forms. From a practical standpoint, thesyntax usage of the MessageBox.Show method can be looked as follows:

    [DialogResult= ] MessageBox.Show([window,]

    prompt

    [, caption]

    [,MessageBoxButtons]

    [,MessageBoxIcon]

    [,MessageBoxDefaultButton]

    [,MessageBoxOptions])

    An explanation of the Show method arguments is shown in the list below:

    window The window that the message box will display in front of (for example,you could specify "Me" to refer to the current form). This argument is

    typically omitted.prompt The text to display in the message box. This is the only required

    argument

    caption The text to display in the title bar of the message box. If omitted, theproject name will be displayed.

    MessageBoxButtons Specifies which buttons to display on the message box. Possiblevalues are:

    MessageBoxButtons.AbortRetryIgnore(displays the Abort,Retry, and Ignore buttons)

    MessageBoxButtons.OK(displays the OK button)

    MessageBoxButtons.OKCancel(displays the OK and Cancelbuttons)

    MessageBoxButtons.RetryCancel(displays the Retry and

    Cancel buttons)

    MessageBoxButtons.YesNo(displays the Yes and Nobuttons)

    MessageBoxButtons.YesNoCancel (displays the Yes, No,and Cancel buttons)

    MessageBoxIcon Specifies which icon to display on the message box. Possible valuesare:

    Value Icon

    http://www.thevbprogrammer.com/vbnet_08/08-00A1-MsgBoxDemo.ziphttp://www.thevbprogrammer.com/vbnet_08/08-00A1-MsgBoxDemo.ziphttp://www.thevbprogrammer.com/vbnet_08/08-00A1-MsgBoxDemo.ziphttp://www.thevbprogrammer.com/vbnet_08/08-00A1-MsgBoxDemo.zip
  • 8/11/2019 Visual Basic Message Box

    9/11

    MessageBoxIcon.Error- or -MessageBoxIcon.Hand- or -MessageBoxIcon.Stop

    MessageBoxIcon.Question

    MessageBoxIcon.Exclamation- or -MessageBoxIcon.Warning

    MessageBoxIcon.Asterisk- or -MessageBoxIcon.Information

    MessageBoxIcon.None(none)

    MessageBoxDefaultButton Specifies the default button for the message box. Possible values are:

    MessageBoxDefaultButton.Button1 (the first message boxbutton is the default button)

    MessageBoxDefaultButton.Button2 (the second message boxbutton is the default button)

    MessageBoxDefaultButton.Button3 (the third message boxbutton is the default button)

    MessageBoxOptions Allows specialized options to be specified. Possible values are:

    MessageBoxOptions.DefaultDesktopOnly (displays themessage box on the active desktop)

    MessageBoxOptions.RightAlign(displays the message box textright-aligned)

    MessageBoxOptions.RtlReading (displays the text in right-to-leftreading order)

    MessageBoxOptions.ServiceNotification (displays the message

    box on the active desktop, even if there is no user logged on to thecomputer)

    Return values from MessageBox are returned in a DialogResult (Integer) datatype. Possible values forDialogResult are:

    Value Description

    DialogResult.OK The OK button was pressed

    DialogResult.Cancel The Cancel button was pressed

    DialogResult.Abort The Abort button was pressed

    DialogResult.Retry The Retry button was pressed

    DialogResult.Ignore The Ignore button was pressed

    DialogResult.Yes

    TheYes button was pressed

    DialogResult.No The Nobutton was pressed

    DialogResult.None Nothing is returned from the dialog box. This means that the modaldialog continues running.

    Sample MessageBox statements along with their corresponding display are shown below:

    Statement Display

  • 8/11/2019 Visual Basic Message Box

    10/11

    MessageBox.Show("Hello there!")

    MessageBox.Show _

    ("The Last Name field must not be

    blank.", _"Last name", _

    MessageBoxButtons.OK, _MessageBoxIcon.Exclamation)

    MessageBox.Show _

    ("A bad database error has

    occurred.", _

    "UpdateCustomerTable", _

    MessageBoxButtons.OK, _

    MessageBoxIcon.Error)

    DimintResponse AsDialogResult

    intResponse = MessageBox.Show _

    ("Are you sure you wantto quit?", _

    "Quit", _

    MessageBoxButtons.YesNo,_

    MessageBoxIcon.Question)

    IfintResponse = DialogResult.Yes Then

    ' end the programEndIf

    DimintResponse AsDialogResult

    intResponse = MessageBox.Show _("Are you sure you want to

    " & _

    "delete all of the rows "

    & _

    "in the Customer table?",_

    "Delete", _

    MessageBoxButtons.YesNo,

    _

    MessageBoxIcon.Question,_

    MessageBoxDefaultButton.B

  • 8/11/2019 Visual Basic Message Box

    11/11

    utton2)

    IfintResponse = DialogResult.Yes Then' delete the rows ...

    EndIf

    The second sample project for this topic contains a command button for each MessageBox examplegiven above.