Hey!

I have a problem with parent and child windows. How do I set the main program to parent window and the other windows to child? I also wanna be able to change a line of text in the main (parent) window from a textbox in a child window. How would I do that?


Thanks in advnace!
//Andreas

There is a variety of ways to do this. I will show you the one I use most often.

It all boils down to variable scoping. Form2 (child) needs to be able to see Form1(parent).
There are two properties in a Form (Parent and ParentForm), however you can not rely upon them being set because of the number of ways to create a form.
Therefore, what I typically do is pass the main form instance to the child form constructor.

private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            Form2 myForm = new Form2(this);
            myForm.Show();
        }

Now, you need to have Form2 store the instance.

public partial class Form2 : Form
    {
        Form1 myParent = null;

        public Form2(Form1 myParent)
        {
            InitializeComponent();
            this.myParent = myParent;
        }

Once the child has this instance you can call any public method or property in the parent form. So in this example, I selected to set the modifier property of a button on the main form to public. Now Form2 can set the text of form1's button like this:

private void button1_Click(object sender, EventArgs e)
        {
            
            myParent.button2.Text = "Foo";
        }

Hope this helps,

Jerry

Thank you! I'm gonna give this a try.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.