简体   繁体   English

在C#中从子窗口访问父窗口中的控件

[英]accessing control in parent window from child window in c#

I have a main "parent" window contains a button and a textbox. 我有一个主“父”窗口,其中包含一个按钮和一个文本框。 I have another window "child" window which fires when I enter some text in the textbox and click the button on the main window. 我有另一个窗口“子”窗口,当我在文本框中输入一些文本并单击主窗口上的按钮时会触发。 now the child window contains another textbox and a button. 现在,子窗口包含另一个文本框和一个按钮。 what I need to do is to enter some text in the textbox on child window then when I hit the button on the child window the textbox on parent window should get updated with the text I entered from the child window.. here is the sample: 我需要做的是在子窗口的文本框中输入一些文本,然后当我在子窗口上单击按钮时,父窗口上的文本框应使用我从子窗口输入的文本进行更新。.这是示例:

Form1.cs Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 tempDialog = new Form2(this);
            tempDialog.ShowDialog();
        }

        public void getText(string text)
        {
            textbox1.Text = text;
        }

    }
}

Form2.cs Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
    public partial class Form2 : Form
    {
        private Form1 m_parent;

        public Form2(Form1 frm1)
        {
            InitializeComponent();
            m_parent = frm1;
        }

        private void button1_Click(object sender, EventArgs e)
        { 
            m_parent.getText(textbox1.text);
        }
    }
}

any idea how to do this? 任何想法如何做到这一点?

1) In Form2 (The child one): Add a property to get the text which wrote in the TextBox: 1)在Form2中(子级):添加一个属性以获取在TextBox中编写的文本:

Public string TheText
{
     get { return textbox1.Text; }
}

And set the button DialogResult property to Ok to know that the user press Ok when he closes the form, not the close button. 并将按钮DialogResult属性设置为“ Ok以知道用户在关闭表单时(而不是关闭按钮)按了“确定”。

2) In Form1 (The parent): Check if the user pressed Ok button, add take the value from the property theText in Form2. 2)在Form1(父级)中:检查用户是否按了“确定”按钮,从Form2中的theText属性中添加take值。

private void button1_Click(object sender, EventArgs e)
{
   Form2 tempDialog = new Form2();
   if (tempDialog.ShowDialog() == DialogResult.Ok)
      textbox1.Text = tempDialog.TheText;
}

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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