messagebox that gives a yes or no option?

stefonalfaro

Member
Joined
Dec 3, 2007
Messages
16
Programming Experience
Beginner
How do I make a messagebox that gives a yes or no option. If the user clicks yes then 'me.close' but if the user click no nothing happens and the message box closes. Ok this gets me the messagebox but how do I get the button to do something

MessageBox.Show("Are you sure you want to close?", "You sure?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
 
Last edited:
VB.NET:
        Dim drAnswer As DialogResult = MessageBox.Show("Are you sure you want to close?", "You sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If drAnswer = DialogResult.Yes Then
            Console.WriteLine("Yes was pressed")
            Me.close()
        Else
            Console.WriteLine("No was pressed")
        End If
 
Last edited:
MessageBox.Show is a function method. Function methods return a value when you call them. You have to check what this value is. You can do this two ways that is more or less a readability choice here:
VB.NET:
If MessageBox.Show(...) = "the DialogResult value you seek" Then
When you press the "=" character the intellisense present you with all values that the Show method can return because the return type DialogResult is an enumeration type, ie a small set of possible values.

Other option, get the value first, then investigate it:
VB.NET:
Dim value As DialogResult = messagebox.show(...)
If value = "the DialogResult value you seek" Then
 
VB.NET:
        Dim intAnswer As Integer = MessageBox.Show("Are you sure you want to close?", "You sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If intAnswer = DialogResult.Yes Then
            Console.WriteLine("Yes was pressed")
            Me.close()
        Else
            Console.WriteLine("No was pressed")
        End If

Yeah I tried that and it worked.
 
Return type is DialogResult which is an enum of integers. If you have Option Strict Off then the compiler won't complain. However, it is good practice to use Option Strict On.
 
True, and using correct type you practically get intellisense to write the code for you.
VB.NET:
Dim intAnswer As Integer
If intAnswer = ... no choices!?
You really gotta type here, and what type was it again? MsgBoxResult? ;)
VB.NET:
Dim intAnswer As DialogResult
If intAnswer = ... here you go !! :)
Select option with mouse or keyboard from the list. Try writing "y" {Enter}.
 
Back
Top