tags:

views:

187

answers:

3

I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:

OtherForm newForm=new OtherForm();
newForm.Show();

How can i communicate from the new winform with the form that opened it? So that I can add some items in it.

+2  A: 

The simplest way is to override the constructor, eg, OtherForm newForm=new OtherForm(string title, int data);. This also works for reference types (which would be a simple way to send the data back).

Factor Mystic
+2  A: 

In the constructor for the other form add a reference to your main form. Then make public/internal anything on the main form that you need to access.

Form m_mainForm;
public OtherForm(Form mainForm)
{
    m_mainForm = mainForm;
}

Edit:

In response to your second post - You might also consider exposing the necessary values you need to create you item. For example, if you need a first name and last name to create a new "person" item, you could expose those as properties in the dialog. That would help to disconnect it a little and make it a little more general purpose.

Of course, your solution works as well, and only you know what will work best in your design.

Jon B
A: 

I think I have found the answer here: http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx

I have to use delegates. In the second form I define:

public delegate void AddItemDelegate(string item);
public AddItemDelegate AddItemCallback;

And from the form that opened it I write:

private void btnScenario2_Click(object sender, EventArgs e)
{

    FrmDialog dlg = new FrmDialog();
    //Subscribe this form for callback
    dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);
    dlg.ShowDialog();

}
private void AddItemCallbackFn(string item)
{

    lstBx.Items.Add(item);

}
netadictos