父表单面板内的子表单如何在单击按钮时访问父表单控件

How can a subform inside a panel of parentform access parent form controls on button click

我有一个父窗体,它有一个文本框 1、一个面板 1 和一个按钮 1。单击 button1,我在 panel1 中打开另一个表单(比如 form2)。 form2 有一个文本框和按钮。当我在文本框中输入一个值并单击子窗体中的按钮时,子窗体的文本框值应该被复制到父窗体的文本框值并且 panel1 应该变得不可见。

我使用下面的代码, 对于 button1 单击(父窗体),

        panel1.Visible = true;
        Form2 f2 = new Form2();
        f2.TopLevel = false;
        f2.AutoScroll = true;
        panel1.Location = new Point(this.ClientSize.Width / 2 - panel1.Size.Width / 2, this.ClientSize.Height / 2 - panel1.Size.Height / 2);
        panel1.Anchor = AnchorStyles.None;
        panel1.Controls.Add(sp);
        f2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        f2.Dock = DockStyle.Fill;
        f2.usrnam = this.usrnam;
        f2.connectionstring = this.connectionstring;
        f2.Show();

对于子表单的按钮点击,

        string s = textBox1.Text;
        Form1 f1= new Form1(); /* However this line is wrong , I donot want to initialize the form again i just need a way to access Form1 controls */
        f1.panel1.Visible = false;
        f1.textBox1.Text = s;

在两种形式中创建形式 objects。类似于:

在parent形式中:

public System.Windows.Forms.Form MyChild

panel1.Visible = true;
Form2 f2 = new Form2();
f2.MyParent = this;
this.MyChild = f2;
-------
-------
f2.Show();

在child中:

public System.Windows.Forms.Form MyParent;

string s = textBox1.Text;
Form1 f1 = (Form1)this.MyParent;
f1.panel1.Visible = false;
f1.textBox1.Text = s;

并且您需要将这些控件的 access modifiers 设置为 public

在构造函数中传递 form1,然后在 form 2 中保留它的本地副本

Form2 f2 = new Form2(this);
Form1 f1=null;

public Form2( Form1 f1)
{
   this.f1=f1;
}

表格 2 代码

string s = textBox1.Text;
f1.panel1.Visible = false;
f1.textBox1.Text = s;