0

Communication between form can be done in many ways using constructor using delegates etc in .net but my question is how can i access a value that is entered into a child form from a parent form or can a two way communication is possible between windows forms.

Nighil
  • 4,099
  • 7
  • 30
  • 56

1 Answers1

7

Provide the values of the child form as properties that can be accessed from the parent form.

E.g.

using ( var form = new ChildForm() )
{
    form.SomeValue = "abc";
    if ( form.ShowDialog(this) == DialogResult.OK )
    {
        var x = form.SomeValue;
    }
}

Use this block in your parent form to pass values to and from the child form.

In the child form, the SomeValue property can map to e.g. a TextBox:

public string SomeValue
{
    get { return MyTextBox.Text.Trim(); }
    set { MyTextBox.Text = value; }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    That property violates an assumption the user of the class has on how properties will work. Mainly, if you set it, and then get it, they should be the same value. In your case, that might not be true. Probably isn't a big deal, but just something to keep in mind. – Bryan Jan 10 '11 at 16:52
  • You refer to the `Trim()`, right? I learned that it sometimes is a big issue for customers if they accidentially enter spaces at the beginning or end, so I do the `Trim()` in critical situations. – Uwe Keim Jan 10 '11 at 16:58
  • 1
    Yes, that is what I'm talking about. I just think you should add a `Trim()` to the `value` as well. But of course, if you do that, you need to check it for null first. – Bryan Jan 10 '11 at 19:27