簡體   English   中英

如何在C#中從子窗口訪問和更改父窗口控件的值

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

嗨,如何從子窗口更改父窗口中文本框的文本值。

即我有父窗口有textbox1和按鈕,子窗口有textbox2和按鈕。 在子窗口的textbox2中輸入一些文本時,我需要更新textbox1的值。

我做了一些簡單的功能來做到這一點在邏輯上是正確的,但它不起作用我不知道為什么。

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

任何想法將不勝感激謝謝

或簡單:在ParentWindow中

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

在子窗口中

this.Owner.Title = "Change";

這很酷

您正在創建另一個“父”窗口(不可見)並更改其文本。 真正的父母必須由孩子訪問。 您可以通過在父母的button1_click中設置的子屬性來執行此操作。

例如

在兒童班

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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM