简体   繁体   中英

Pop up window gives an error on mdi form in C#

I have a form that works fine on its own, but I want to add it to an mdi parent form.

The problem is that I have a small form that pops up, asks for info, then passes the info to the original form.

I use this to pop up the form:

Form2 fm = new Form2();

if (fm.ShowDialog(this) == DialogResult.OK)
{
    //do stuff
}

I get an error on the first line of form2 (the pop up form):

Form1 fm2 = (Form1)this.Owner;

fm2.lbText = this.textBox1.Text;

Again, this all works fine if form1 is a standalone form; but if I make it a child form I get this error when I click on OK on form2 to return to form1 .

Message=Unable to cast object of type 'Partsbuddy2._0.Menu' to type 'Partsbuddy2._0.Form1'.

this.Owner is apparently not the form but the Menu. Apparently one of the strange things that happen when you change to MDI

Instead of using the Owner property, you can add your own property to the Form2 , containing the reference to the owner form:

public Form OwnerForm {get; set;}

and then when creating the new Form2 instance, use:

Form2 fm = new Form2() { OwnerForm = this };

and in the Form2 you use this to access Form1 :

Form1 fm2 = (Form1)this.OwnerForm;

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