C# Winform show menu on left in UI(Subform is displayed on the main form)

Lionsure 2020-08-09 Original by the website

Winforms can also display menus on the left and a sub-form(web page) is shown on the right when clicking a menu, like a website, but the sub-form cannot be displayed directly in the main Form because the Form is not a control. So can the Form be set as a control? The answer is yes, as long as the Dock property of Form is set to Fill, it becomes a control. After it is converted into a control, it can be added to the Panel control like other controls, it also realizes the left display menu and the right display content.

 

Knowing the method of displaying the menu on the left and displaying the subform on the main Form, then look at how to implement it with code. The specific steps and code are as follows:

1. Drag a Panel control to the left of the main Form to display the left menu, named panelLeftMenu.

2. Drag another Button control to panelLeftMenu, keep the default name Button1.

3. Finally, drag a Panel control to the right of the main Form and name it PanelRightMain.

 

4. Create a new subform with the file name SubForms.cs; in order to see the effect easily, drag a Label and TextBox control to the subform.

5. Double-click Button1 to open the background code file, and add the code to display the subform in the main Form in the button1_Click(object sender, EventArgs e) method. The detailed implementation is as follows:

private void button1_Click(object sender, EventArgs e)
        {
                SubForms sub = new SubForms();
                sub.TopLevel = false;
                sub.Dock = DockStyle.Fill;//Set the subform as a control

        sub.FormBorderStyle = FormBorderStyle.None;
                PanelRightMain.Controls.Add(sub);
                sub.Show();
        }

The code running effect is as follows:

C# Winform show menu on left in UI(Subform is displayed on the main form)

The above-mentioned is one of the methods, and there are other methods that can also be implemented.