Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 759
Max Avatar asked Dec 12 '13 18:12

Max


People also ask

What is ShowDialog C#?

ShowDialog() Shows the form as a modal dialog box. ShowDialog(IWin32Window) Shows the form as a modal dialog box with the specified owner.

What is a dialog box in VB?

Dialog boxes are used to interact with the user and retrieve information. In simple terms, a dialog box is a form with its FormBorderStyle enumeration property set to FixedDialog . You can construct your own custom dialog boxes by using the Windows Forms Designer in Visual Studio.


1 Answers

The simplest method is to add a public property to the frmOptions form that returns an internal string declared at the global level of the frmOptions

Dim strValue As String
Public Property MyStringValue() As String
    Get
       Return strValue
    End Get
End Property

Then, when your user clicks the OK button to confirm its choices you copy the value of the textbox to the internal variable

Private Sub cmdOK_Click(sender As Object, e As System.EventArgs) Handles cmdOK.Click
    strValue = txtMyTextValue.Text
End Sub

Finally in the frmMain you use code like this to retrieve the inserted value

Private Sub ShowOptionsForm()
    Using options = New frmOptions()
       if DialogResult.OK = options.ShowDialog() Then
          Dim value = options.MyStringValue
       End If
    End Using
End Sub

I prefer to avoid direct access to the internal controls of the frmOptions, a property offer a indirection that could be used to better validate the inputs given by your user.

like image 190
Steve Avatar answered Sep 19 '22 16:09

Steve