简体   繁体   中英

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..

ie 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

or simple: in the ParentWindow

ChildWindow child = new ChildWindow(); 
child.Owner = this;
child.ShowDialog();

in the child window

this.Owner.Title = "Change";

this works pretty cool

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.

eg

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)

Don't create a new parent. Reference the parent of the form itself.

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

And this is how you first create the child:

    private void button1_Click(object sender, EventArgs e)
    {
        //Display modal dialog
        child myform = new child();
        myform.ShowDialog(this);  // make this form the parent
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM