How to get values from a dialog form in VB.NET?

dialog, modal-dialog, textbox, vb.net, winforms

Solution

You want to capture the information from the dialog only if the result is `OK` (user presses `Save` instead of `Cancel` or closes the dialog some other way), so do this:

Private Sub ShowOptionsForm()
    Dim options = New frmOptions

    ' Did the user click Save?
    If options.ShowDialog() = Windows.Forms.DialogResult.OK Then
        ' Yes, so grab the values you want from the dialog here
        Dim textBoxValue As String = options.txtMyTextValue.Text
    End If
End Sub

Now inside of your dialog form, you need to set the result `Windows.Forms.DialogResult.OK` when the user clicks the button that corresponds to the `OK` action of the dialog form, like this:

Public Class frmOptions
    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        ' Set the result to pass back to the form that called this dialog
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub
End Class

Problem

I have a "frmOptions" form with a textbox named "txtMyTextValue" and a button named "btnSave" to save and close the form when it's clicked, then, I'm showing this dialog form "frmOptions" when a button "btnOptions" is clicked on the main form "frmMain", like this ``` Private Sub btnOptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOptions.Click ShowOptionsForm() End Sub Private Sub ShowOptionsForm() Dim options = New frmOptions options.ShowDialog() End Sub ``` How can I get in the main form "frmMain" the value inserted in the textbox "txtMyTextValue" when the "btnSave" is clicked?

Original source