Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a value from a ShowDialog window?

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.

like image 874
Landmine Avatar asked Jul 31 '13 22:07

Landmine


3 Answers

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).

like image 92
Styxxy Avatar answered Sep 28 '22 04:09

Styxxy


You should set the AcceptButton and the CancelButton property on the Form, but also, the AcceptButton should have its property DialogResult set to OK and the CancelButton to Cancel.

In this way, when your user presses one of these buttons the ShowDialog call returns and you can check the return value using the predefined values in the enum DialogResult

DoSomething()
Dim result = My.Forms.frmMessage.ShowDialog(Me)
If result = DialogResult.OK Then
   ' Do Code
   DoCode()
Else
  ' Cancel Button Pressed
   DoOtherCode()
End If
DoMore()
like image 45
Steve Avatar answered Sep 28 '22 04:09

Steve


The answers by Styxxy and Steve both work for handling the DialogResult in the main window. However the DialogResult property for the Accept button should not be set in the properties window, it should be set in your code after validation occurs. This way if the user inputs bad data in the form they can get an error message and fix it without losing any work, instead of starting over.

'code in Dialog Form
Private Sub btnAccept_Click(sender As System.Object, e As System.EventArgs) Handles btnAccept.Click
    If IsValid() = True Then
        DialogResult = Windows.Forms.DialogResult.OK
    End If
End Sub
like image 35
Wayne Avatar answered Sep 28 '22 02:09

Wayne