How can I return a value from a ShowDialog window?

Landmine picture Landmine · Aug 1, 2013 · Viewed 44.8k times · Source

frmMain

DoSomething()
My.Forms.frmMessage.ShowDialog(Me)
If AcceptButtonClicked Then
' Do Code
DoCode()
Else
' Cancel Button Pressed
DoOtherCode()
End If
DoMore()

frmMessage

My.Forms.frmMain.AcceptButtonClicked = True

Is there a way to pass a value from a Dialog window back to a paused thread on the main window? I want to know if they pressed the Ok or Cancel Button after filling out a form that pops up.

Answer

Styxxy picture Styxxy · Aug 1, 2013

You can use the DialogResult property on your form. This value will be returned by the ShowDialog function you call. You can also set this property on your buttons so WinForms will handle the setting of the form property.

In your frmMessage you'll have to set the property accordingly (pick the one you need, OK and Cancel). Then you can check the return value easily:

If My.Forms.frmMessage.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
    ' OK button pressed
    DoCode()
Else
    ' Cancel button pressed
    DoOtherCode()
End If

Don't forget that the user might be able to close the form in another way than closing it with your buttons (e.g. by closing it with the close button).