Passing data between two open Forms (neither is MDI)

V

VMI

I have a Windows Form Form1 (not MDI) and when I double-click on the Form,
another Form2 will "pop up". How can I pass the text that I typed in Form2
to a textbox in Form1? I was thinking if it was possible that from Form2 I
can call a public method in Form1 that updates the Textbox. I wanted to use
something similar to the following code:

Form[] childForm = this.MdiParent.MdiChildren ;
Form f=null;
f=(Form)childForm[0];
frm_interactive frmInteractive=f as frm_interactive; //frm_interactive is
already open
frmInteractive.runAddress("my text"); //public method

Any help is appreciated. I'm using VS2005.

Thanks.
 
B

bob

Hi,
You could add a custom event to form2
and handle it in Form1.

1) Derive a class from eventargs to carry the payload.
public class TraceMessageEventArgs:System.EventArgs
{
private string mstrTraceMessage;

public TraceMessageEventArgs(string strMessage)
{
mstrTraceMessage = strMessage;
}
public string TraceMessage
{
get { return mstrTraceMessage; }
set { mstrTraceMessage = value; }
}

}

2) In form 2 Declare the event
public delegate void TraceMessageEventHandler(TraceMessageEventArgs
e);
public event TraceMessageEventHandler SMSTraceMessage;

3) In Form 1 handle the event by adding the eventhandler to your
form2 variable.
form2 f =new form2();
f.SMSTraceMessage += new TraceMessageEventHandler(te_TraceMessage);
void te_TraceMessage(TraceMessageEventArgs e)
{
this.listBox1.Invoke(new dTraceMessage(ListMessage), new
object[] { e.TraceMessage }); //dTraceMessage is a delegate,
avoiding cross threading issues.
}

4) Raise the event with its payload at the appropriate point(s) in
form2

TraceMessageEventArgs ex =newTraceMessageEventArgs(MyTextbox.text);
SMSTraceMessage(ex);

HTH
Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top