简体   繁体   中英

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

I have a parent form which has a textbox1 and a panel1 and a button1. I open another form(say form2) in panel1 on button1 click. form2 has a textbox and button. when i enter a value in textbox and click on the button in subform , the textboxvalue of subform should be copied to textbox value of parent form and panel1 should become invisible.

I use the following code, For 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();

For button click of subform,

        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;

Create form objects in both forms. Something like:

In parent form:

public System.Windows.Forms.Form MyChild

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

In child:

public System.Windows.Forms.Form MyParent;

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

And you need to make the access modifiers of those controls to public .

pass form1 in the constructor an then keep a local copy of it in form 2

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

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

form 2 code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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