Search code examples
c#controlsparent

How to access and change value of parent window control from child window in C#


Hi how can I change text value of text box in parent window from child window..

i.e I have parent window have textbox1 and button and child window has textbox2 and button. I need to update the value of textbox1 when I enter some text in child window's textbox2.

i did some simple function to do this logically its correct but its not working I have no idea why..

parent.cs

namespace digdog
{
    public partial class parent : Form
    {
        public parent()
        {
            InitializeComponent();
        }

        public void changeText(string text)
        {
            textbox1.Text = text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Display modal dialog
            child myform = new child();
            myform.ShowDialog();

        }

    }
}

child.cs

namespace digdog
{
    public partial class child : Form
    {

        public child()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
         parent mytexts = new parent();
         mytexts.changeText(textbox2.Text);
        }
    }
}

any ideas will be appreciated thanks in advance


Solution

  • You are creating another 'parent' window (which is not visible) and changing its text. The 'real' parent needs to be accessed by the child. You could do this via a property on the child that is set in the parents button1_click.

    e.g.

    in child class

    public parent ParentWindow {get;set;}
    

    in parent button1_click

    child myform = new child();
    child.ParentWindow = this;
    m.ShowDialog();
    

    in child button1_click

    ParentWindow.changeText(textbox2.Text)