Search code examples
c#winformsdynamicpanel

How to switch panels dynamically in Windows Forms


I am new to C# and am working on a C# Windows Forms application in Visual Studio and want to dynamically replace existing panel A in Form with another panel B.

One of the ways this can be achieved is by placing panels on one another such that their upper left corners overlap each other. But this approach makes it difficult to make changes to panels placed beneath.

I have done this type of work in Java but haven't found any solution for Windows Forms.


Solution

  • As you have specified you don't want to panels, then use a TabControl

    At either run time, or at design time

    1. Set Appearance to Buttons

    2. Set ItemSize 0 for Width and 1 for Height

    3. Set Multiline to True

    4. Set SizeMode to Fixed

    The tabs on the tab pages should now not be visible, but the tabpages are still there.

    However it will also allow you to work with the controls on each page a bit more easily

    Update from comments

    Another way to do this is inheriting from TabControl

    as seen here See Creating Wizards for Windows Forms in C#

    class WizardPages : TabControl {
      protected override void WndProc(ref Message m) {
        // Hide tabs by trapping the TCM_ADJUSTRECT message
        if (m.Msg == 0x1328 && !DesignMode) m.Result = (IntPtr)1;
        else base.WndProc(ref m);
      }
    }