【问题标题】:How to access and change value of parent window control from child window in C#如何在 C# 中从子窗口访问和更改父窗口控件的值
【发布时间】:2010-11-11 23:48:38
【问题描述】:

嗨 如何从子窗口更改父窗口中文本框的文本值..

即我的父窗口有 textbox1 和按钮,子窗口有 textbox2 和按钮。 当我在子窗口的 textbox2 中输入一些文本时,我需要更新 textbox1 的值。

我做了一些简单的功能来做到这一点在逻辑上它是正确的,但它不起作用我不知道为什么..

父.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);
        }
    }
}

任何想法将不胜感激 提前谢谢

【问题讨论】:

  • 不到一小时前的重复问题:stackoverflow.com/questions/4160143/…
  • 我将其简化,以便获得更多答案。你有什么问题吗?
  • @RobinVanPersi:最好编辑你的问题而不是发布两次。

标签: c# controls parent


【解决方案1】:

或者简单的: 在父窗口中

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

在子窗口中

this.Owner.Title = "Change";

这很酷

【讨论】:

  • 如果有人感兴趣,可以使用这样的 ShowDialog 所有者参数 [ child.ShowDialog(this); ] 用少一行实现了相同的结果。此外,这个参数让我相信这是预期的目的。
【解决方案2】:

您正在创建另一个“父”窗口(不可见)并更改其文本。孩子需要访问“真正的”父母。您可以通过在父 button1_click 中设置的子属性来执行此操作。

例如

在子类中

public parent ParentWindow {get;set;}

在父按钮1_click

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

在子按钮 1_click 中

ParentWindow.changeText(textbox2.Text)

【讨论】:

  • @ermac2014 和@grantnz;是的,这行得通,但您不需要将ParentWindow 实现为“子”表单的属性;如您在我的回答中所见,该属性已存在于 .NET 的 Form 类中。
【解决方案3】:

不要创建新的父级。引用表单本身的父级。

    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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多