Home > Back-end >  Using objects and classes of one form in another form
Using objects and classes of one form in another form

Time:07-18

The issue is quite complex. I have Main form which we shall call mainForm, another secondForm and thirdForm. secondForm opens inside a panel in mainForm using a method which is under the class of mainForm. I want to open thirdForm inside the panel of mainForm but through a click event occurring in secondForm using the same method which is under mainForm's class. This means that l have to call that method, but l want to do it without altering it's declation to static' Anyone with a good way of achieving that.The method is right below.

public void OpenChildForm(Form ChildForm)
    {
        if (activeForm != null)
        {
            activeForm.Close();
            activeForm = ChildForm;
            ChildForm.TopLevel = false;
            ChildForm.FormBorderStyle = FormBorderStyle.None;
            ChildForm.Dock = DockStyle.Fill;
            panelChildForm.Controls.Add(ChildForm);
            panelChildForm.Tag = ChildForm;
            ChildForm.BringToFront();
            ChildForm.Show();
        }
         else
        {
            activeForm = ChildForm;
            ChildForm.TopLevel = false;
            ChildForm.FormBorderStyle = FormBorderStyle.None;
            ChildForm.Dock = DockStyle.Fill;
            panelChildForm.Controls.Add(ChildForm);
            panelChildForm.Tag = ChildForm;
            ChildForm.BringToFront();
            ChildForm.Show();
        }
    }

CodePudding user response:

In secondForm you can get a reference to mainForm via the ParentForm property:

// in ...secondForm ...
mainForm mf = this.ParentForm as mainForm;
if (mf != null) {
    thirdForm tf = new thirdForm();
    mf.OpenChildForm(tf);
}
  • Related