【问题标题】:How can a subform inside a panel of parentform access parent form controls on button click父窗体面板中的子窗体如何在单击按钮时访问父窗体控件
【发布时间】:2015-05-02 19:53:43
【问题描述】:

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

我使用以下代码, 对于 button1 click(of parentform),

        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;

【问题讨论】:

  • 为什么不在构造函数中传递form1,然后在form 2中保留它的本地副本?

标签: c# forms panels


【解决方案1】:

在两种表单中创建表单对象。比如:

在父表单中:

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

【讨论】:

  • 嗨@RagingBull 它只是做了一些小的修改,我只是添加了一行,Form1 f1 = (Form1)this.MyParent; f1.panel1.Visible = 假; f1.MyParent.textBox1.Text = s;非常感谢.....:) :)
【解决方案2】:

在构造函数中传递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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多