Passing value from child to mdi parent in VB.net

Mussnoon picture Mussnoon · Feb 19, 2009 · Viewed 14.3k times · Source

I have a simple contact book. The application has a main window that's an mdi form. When a contact is added using the "add a contact" form, I want to show a simple feedback message in the parent window status bar saying that the contact was added successfully.

Here's the child loading:

Private Sub addButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addButton.Click
    Dim af As New addForm
    af.MdiParent = Me
    af.Show()
End Sub

The problem is that since the parent is actually an mdi parent, and the "add a contact" form is launched with .Show() instead of .ShowDialog(), I can't store any return value that can be used by the launching Sub to perform an action.

Is there a way to pass a value from this child to the mdi parent? Here's the child form doing it's stuff:

Private Sub addButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addButton.Click

    Dim contact = <contact>
                      <quickName><%= quickNameTextBox.Text %></quickName>
                      <firstName><%= firstNameTextBox.Text %></firstName>
                      <lastName><%= lastNameTextBox.Text %></lastName>
                      <email><%= emailTextBox.Text %></email>
                      <website><%= websiteTextBox.Text %></website>
                      <telephone><%= telephoneTextBox.Text %></telephone>
                      <mobile><%= mobileTextBox.Text %></mobile>
                  </contact>

    Dim contactList = XDocument.Load("contactList.xml")

    contactList.Elements()(0).Add(contact)
    contactList.Save("contactList.xml")
    //something here to trigger the status update in the parent?
    //trivia: SO doesn't support VB single-quote comments...
    Me.Close()

End Sub

P.S. Apparently, I'm rather bad at tagging things...so anyone wanting to retag this question are most welcome.

Answer

jgallant picture jgallant · Feb 19, 2009

The way I would handle this, is to create a custom event on the child control. Then handle the event on the parent control.

First, define the event in the child control (example, define your own):

Public Event EVENTNAME(ByVal sender as Object, ByVal ValueToReturn As String)

Then, raise the event on the child control when your data is ready to be passed.

RaiseEvent EVENTNAME(Me, txtBoxWithReturnValue.Text)

Once you got that done, on the parent form now, you may handle the custom event. To do this, you need to add a listener, to "listen" for the event when it fires:

AddHandler CONTROLNAME.EVENTNAME, AddressOf EVENTNAME

Then, you may write a routine to handle this new event in your parent form:

Private Sub FUNCTIONAME(ByVal sender As System.Object, ByVal ValueToReturn as String) Handles CONTROLNAME.EVENTNAME

'Code to handle data here

End Sub