开发者

Passing form as parameter when creating new form

开发者 https://www.devze.com 2023-02-17 11:29 出处:网络
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

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();
     开发者_StackOverflow中文版   }

... 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号