Search code examples
vb.netshowshowdialog

VB.NET: What is the best way to retrieve a value from a second form?


I'm teaching myself VB.Net.

Here is a problem I have recently come across. Say I have a main Form1 in my application. Form1 calls a second LoginForm which (like the name suggests) is a login window with username/password type fields. Expected behaviour is that LoginForm will capture login details and pass them back to Form1.

What is the best way to do this?

In my mind, I was thinking along the lines of a function call like 'doLogin' that would 'show' the LoginForm, capture the data entered, dispose of the form and return the login details (probably in some kind of bean). Somehow I don't see this as being possible

What I have currently is less elegant. LoginForm is shown by Form1 modally (i.e. showDialog); a 'me' reference is passed to the second window. After user input has been received on LoginForm, I set a value on Form1, then dispose.

Is this the way everybody does it?


Solution

  • I've always passed in a delegate to the second form which can be called to 'pass back' the values from the second form into the first.

    That way you are avoiding any tight coupling.

    Classic observer pattern.


    An example implementation is as follows:

    Add a delegate signature to Form1. In Form1's button click event handler, instantiate the Form2 class and Form1's delegate. Assign a function of Form2 to the delegate, and call the delegate:

    'Form1.vb
    Public Delegate Sub delPassData(ByVal text As TextBox)
    
    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
      Dim frm As Form2 = New Form2
      Dim del As delPassData = New delPassData(AddressOf frm.funData)
      del(Me.textBox1)
      frm.Show()
    End Sub
    

    In Form2, add a function to which the delegate will point. This function will assign textBox1's text to label1.

    'Form2.vb
    Public Sub funData(ByVal text As TextBox)
      label1.Text = text.Text
    End Sub
    

    To pass data back to Form1, just make funData a function that returns the values you want.