C# – How to have multiple panels with different controls in a form in C#

cnetwinforms

I am new to C#.Net.
I have a form with some panels in it. One of the panels is MainPanel. After start up, the MainPanel is empty. Based on user selection, I want to load some controls in it. Something similar to CardLayout in Java! Each panel have a lot of Controls and I don't want to add them programatically. In fact the question is "Is there a way to have some panels designed in designer and show/hide them based on user selection, all in one form?"

enter image description here

Thank you.

Best Answer

Yes, create new objects called UserControls in their own classes. You can add and remove them programmatically, but create them in the designer.

To keep from getting flicker when changing the controls, do something like the following:

Control ctlOld = frmMain.Controls[0]; // this will allow you to remove whatever control is in there, allowing you to keep your code generic.
ctlNextControl ctl = new ctlNextControl(); // this is the control you've created in another class
frmMain.Controls.Add(ctlNextControl);
frmMain.Controls.Remove(ctlOld);

Create your User Controls, and name them whatever you wish, I'll make some names up now for examples:

ctlGear
ctlMap
ctlGraph
ctlCar
ctlPerson

Add those 5 files as UserControls to your project. Design them however you want.

Create an enum for the different buttons for ease of use:

public enum ControlType {
    Gear,
    Map,
    Graph,
    Car,
    Person
}

Once you have them created, in the button click events for each of those buttons, add a call to this new method:

private void SwitchControls(ControlType pType) {
    // Keep a reference to whichever control is currently in MainPanel.
    Control ctlOld = MainPanel.Controls[0];
    // Create a new Control object
    Control ctlNew = null;
    // Make a switch statement to find the correct type of Control to create.
    switch (pType) {
        case (ControlType.Gear):
           ctlNew = new ctlGear();
           break;
        case (ControlType.Map):
           ctlNew = new ctlMap();
           break;
        case (ControlType.Graph):
           ctlNew = new ctlGraph();
           break;
        case (ControlType.Car):
            ctlNew = new ctlCar();
            break;
        case (ControlType.Person):
            ctlNew = new ctlPerson();
            break;
        // don't worry about a default, unless you have one you would want to be the default.
    }

    // Don't try to add a null Control.
    if (ctlNew == null) return();

    MainPanel.Controls.Add(ctlNew);

    MainPanel.Controls.Remove(ctlOld);
}

Then in your button click events, you could have something like this:

private void btnGear.Click(object sender, EventArgs e) {
    SwitchControls(ControlType.Gear);
}

The same thing would be in the other click events, just change out the ControlType in the parameters.