transferring data between windows forms

  • Thread starter Thread starter Yasin Cepeci
  • Start date Start date
Hi Yasin,

Create your child form as you would normally.

Modify the child form's constructor and add your own parameters (arguments).
One of these can be a reference to an object (such as a container class,
string, structure, ...) that contains the data you want to pass to your
form.

When you instantiate your child class in the parent class or form, you pass
a reference to the data object (or structure) to your child form's
constructor.

When the child form is instantiated, it will be able to access the data in
this data object. It can also modify it, so when the child form is closed,
the parent can read (get access) to the modified data from the child form.

Example code (in VB). The code is fairly similar in C# and C++:

Define the child form as below:

Public Class Form_Child

Private m_Msg As String

'
' Note: If you also want to modify the msg string so that the user
(parent) will
' see the change, pass msg ByRef instead of ByVal.
'
Public Sub New(ByVal msg As String)
' This call is required by the Windows Form Designer.
InitializeComponent()

' Save the message string passed to us by the user.
m_Msg = msg
End Sub

' Use the String value (m_Msg) and modify it if required in the child
form.
Public Sub Form_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) handle MyBase.Load
MessageBox.Show("My name is " + m_Msg)
End Sub

End Class



In the parent class:

...
Dim myName As String = "Fred"
Dim form As New Form_Child(myName)
form.ShowDialog()
form.Dispose()
...



Hope this helps.

Ramses
 
Back
Top