如何在C#中从子窗口访问和更改父窗口控件的值
您好如何从子窗口更改父窗口中文本框的文本值..
即我有父窗口有textbox1和按钮,子窗口有textbox2和按钮。 当我在子窗口的textbox2中输入一些文本时,我需要更新textbox1的值。
我做了一些简单的function,逻辑上这是正确的,但它不工作我不知道为什么..
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); } } }
任何想法将提前感谢
您正在创建另一个“父”窗口(不可见)并更改其文本。 孩子需要访问“真正的”父母。 您可以通过父项button1_click中设置的子项上的属性来执行此操作。
例如
在儿童class
public parent ParentWindow {get;set;}
在父按钮1_click中
child myform = new child(); child.ParentWindow = this; m.ShowDialog();
在儿童button1_click
ParentWindow.changeText(textbox2.Text)
不要创建新的父级。 引用表单本身的父级。
private void button1_Click(object sender, EventArgs e) { parent mytexts = this.Parent as parent; mytexts.changeText(textbox2.Text); }
这就是你第一次创建孩子的方式:
private void button1_Click(object sender, EventArgs e) { //Display modal dialog child myform = new child(); myform.ShowDialog(this); // make this form the parent }
或简单:在ParentWindow中
ChildWindow child = new ChildWindow(); child.Owner = this; child.ShowDialog();
在子窗口
this.Owner.Title = "Change";
这很酷