父窗体面板中的子窗体如何在单击按钮时访问父窗体控件

本文关键字:窗体 单击 按钮 访问 控件 体面 | 更新日期: 2024-09-22 03:29:24

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

我使用以下代码,对于按钮1点击(父窗体),

        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;

父窗体面板中的子窗体如何在单击按钮时访问父窗体控件

在两种表单中创建表单对象。类似于:

以母版形式:

public System.Windows.Forms.Form MyChild
panel1.Visible = true;
Form2 f2 = new Form2();
f2.MyParent = this;
this.MyChild = f2;
-------
-------
f2.Show();

儿童:

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,然后在form2 中保留它的本地副本

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;