简体   繁体   中英

Passing form as parameter when creating new form

I have a MainForm, which is MDI container. In MainForm, I create 2 new forms, which open on buttonclick - Form1 and Form2. And there is also a 3rd form - CommonFom, which I should be able to open from Form1, and Form2 (on buttonclick). I need 3rd Form to save info if I switch between Form1&2, so I cant create new instances of it from Form1&2. I'm trying to do something like this in MainForm:

CommonForm CF = new CommonForm();
Form1 x = new Form1(CF);
Form2 y = new Form2(CF);

after that, in Form1 and Form2:

public MainForm(CommonForm theCF)
        {
            InitializeComponent();
        }

... somewhere on buttonclick

CF.show();

But it show me error in Form1, than there is no instance of object CF (in line CF.Show()) So how do I do this correctly?

Declare in Form1 and Form2 in the beginning. (since it is missing in the code, I'm not sure about compile error or runtime error)

private Form CF; //The reason I've declared the type as Form is to have flexibility of having any form to show.

Modify each of the constructors of Form1 and Form2 like this.

public MainForm(CommonForm theCF)     
{   
    this.CF = theCF; 
    InitializeComponent();        
}

it should solve your problem.

Use the CommonForm as a singleton: ie provide a static property Instance of type CommonForm inside the CommonForm class, instantiate it the CommonForm constructor. Then you can have everywhere access to CommonForm by using CommonForm.Instance .

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