How to access and change value of parent window co

2020-02-13 06:46发布

问题:

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

回答1:

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)


回答2:

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



回答3:

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
    }