Eljey Shikaku
Eljey Shikaku

Reputation: 55

How to control the panel of MainForm using UserControl?

MainForm myMainForm;

private void ButtonResort_MouseClick(object sender, MouseEventArgs e)
{
    panelSub.Controls.Add(new myUserControl());
}

After adding my myUserControl to my MainForm. How can I add my myUserControl2 to other panel of my MainForm?

public partial class myUserControl : UserControl
{
    MainForm myMainForm;

    public myUserControl()
    {
        InitializeComponent();
    }

    private void Button1_MouseClick(object sender, MouseEventArgs e)
    {
        myMainForm.PanelBody.Controls.Add(new myUserControl2());
    }
}

this is the code I've tried and it just gives me an error. "Object Reference not set to an instance of an object."

Upvotes: 0

Views: 195

Answers (2)

T.S.
T.S.

Reputation: 19404

As alternative way to passing form in constructor, you can do this:

private void Button1_MouseClick(object sender, MouseEventArgs e)
{
    myMainForm = this.FindForm as MainForm;
    if (myMainForm != null)
        myMainForm.PanelBody.Controls.Add(new myUserControl2());
}

If you interested in reusability, you pass form or control in constructor. Form is also derivative of control btw. Same thing with FindForm. If you mention MainForm - it is tightly coupled. If you use form - it could be any form. Usually, people pass actual surface [control] on which to add your new control.

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81583

The problem is your myMainForm has never been set

You can set it in your myUserControl constructor

public partial class myUserControl : UserControl
{
    MainForm myMainForm;

    public myUserControl(MainForm mainForm)
    {
        InitializeComponent();
        myMainForm = mainForm;
    }

    private void Button1_MouseClick(object sender, MouseEventArgs e)
    {
        myMainForm.PanelBody.Controls.Add(new myUserControl2());
    }
}

Usage

panelSub.Controls.Add(new myUserControl(this));

Upvotes: 3

Related Questions