Understanding MessageBox.Show in VB.NET
In VB.NET, the preferred way to display a message dialog is by using the
MessageBox.Show method.
It provides more flexibility and integrates fully with the .NET Framework, offering support for titles, icons, and button sets.
Basic Example
MessageBox.Show("Hello, World")
This displays a standard message box with only an OK button.
Example With a Title
MessageBox.Show("Operation completed successfully.", "Status")
Buttons Example
You can choose different button combinations using MessageBoxButtons:
MessageBox.Show("Are you sure you want to delete this file?",
"Confirm Delete",
MessageBoxButtons.YesNo)
Icons Example
You can show icons using MessageBoxIcon:
MessageBox.Show("An error has occurred.",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Capturing the User's Response
MessageBox.Show returns a value from the DialogResult enumeration, allowing you to see which button the user clicked:
Dim result As DialogResult
result = MessageBox.Show("Save changes before exiting?",
"Exit",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question)
If result = DialogResult.Yes Then
' Save the file
ElseIf result = DialogResult.No Then
' Exit without saving
Else
' Cancel exit
End If
Common MessageBoxButtons Options
| Option | Description |
|---|---|
OK |
Displays only OK |
OKCancel |
OK and Cancel buttons |
YesNo |
Yes and No buttons |
YesNoCancel |
Yes, No, and Cancel buttons |
RetryCancel |
Retry and Cancel buttons |
AbortRetryIgnore |
Abort, Retry, and Ignore buttons |
Common MessageBoxIcon Options
| Icon | Description |
|---|---|
Information |
Information / (i) icon |
Warning |
Yellow warning triangle |
Error |
Red stop/error icon |
Question |
Blue question mark icon |
Why Use MessageBox.Show Instead of MsgBox?
- It is part of the .NET Framework and object-oriented.
- Provides better clarity and type safety.
- Supports more options for buttons, icons, and return values.
- Is the recommended method for VB.NET applications.
MsgBoxremains only for compatibility with VB6.
PeatSoft - VB.NET - Educational Reference - AI