Sharing data between forms

Joined
Mar 26, 2009
Messages
15
Programming Experience
Beginner
Hi,

I have two forms A and B. B is a child of A - i.e. I have a button on A that pops up form B. I want B to be able to access and change data (e.g. an instance of an object etc.) in A and also to call some function in A. At the same time I'd like to preserve the right to alter the data in A without opening B. I've achieved this using the following (i.e. by declaring the object and method as Friend):

VB.NET:
Public Class frmA
   Friend _data as Hashtable

   Friend Sub GetData()
      If _data IsNot Nothing Then
         _data As New Hashtable
         _data.Add("key1","value1")
         _data.Add("key2","value3")
         _data.Add("key3","value3"
      End If
   End Sub

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      Dim frmChild As New frmB(Me)
      frmChild.ShowDialog()
      frmChild.Dispose()
End Sub
End Class

Public Class frmB
    Private _frmParent As frmA

    Public Sub New(ByVal frmParent As frmA)
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _frmParent = frmParent
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       _frmParent.GetData()
       MessageBox.Show(_frmParent._data.Item("key1"))
    End Sub
End Class

Is there anything inherently wrong with the what I've done and if so how can I achieve a similar result? (It seems to work - I can read, add to and change the values in the _data Hashtable from within form B and when B is closed the values persist i.e. I can access the changed values from within form A. I just dont know if its a horrible fudge).

Thanks,

Norman
 
Hi InertiaM,

Thanks for the reply much appreciated.

I had thought of that but there were issues with it? If I pass _data to form B (in the constructor for example or by overriding the ShowDialog method) I still have to access a method (GetData) which resides in form A (unless I duplicate the code which I want to avoid) as I'd like to retain the option of altering _data in form A using the same routine? Also _data might not exist at the point when B is opened (in my example B actual creates _data but equally it could be created from within A). I thought passing objects around could get tricky. If I pass _data by ref in the constructor of form B when _data is Nothing and create _data from within B, _data will not be accessible from A when B closes? I dunno if I'm explaining myself the best.:confused:

Do you have a simple example of passing an object between two forms (as you describe) where the object could be created in either and where you have a single method somewhere that modifies a value in the object?
 
Back
Top