Introduction
I Googled a lot for C# code to create an expandable menu or panel for my application. I got it but I have to write a large amount of code for that and it was time consuming. Why should we waste our valuable time when there is a simple and easy way to create the same??? I am here to explain my way of creating an Expandable/Collapsible Menu. See the following figure:
Using the Code
Follow these steps:
- Create a Windows Form application (e.g.:
frmMain
)
- Add a Panel control and dock it anywhere you want (e.g.:
pnlMenu
)
- Add a Panel inside the main panel (e.g.:
pnlMenu
-> pnlMenuGroup1
)
- Add a Button or any other control like label/picturebox to the inside panel and dock it to Top - It is the Menu Head. (e.g.:
btnMenuGroup1
- Button Height = 25)
- Add Button controls as submenus to the inside panel and dock it to Top. Now it will look like a menu group. (e.g.:
btnAbout
- Button Height = 25)
- Create more "menu groups" like you have created now. (Follow steps 1 to 5.)
- Add Image (Up/Down) to the Button which is going to be your "menu head".
*** Add Picturebox
controls and load images and adjust Transparency to give your window more visual styles.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ExpandablePanelSample
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
Left = Top = 0;
pnlMenuGroup1.Height = 25;
pnlMenuGroup2.Height = 25;
pnlMenuGroup3.Height = 25;
btnMenuGroup1.Image = Properties.Resources.down;
btnMenuGroup2.Image = Properties.Resources.down;
btnMenuGroup3.Image = Properties.Resources.down;
}
private void btnMenuGroup1_Click(object sender, EventArgs e)
{
if (pnlMenuGroup1.Height == 25)
{
pnlMenuGroup1.Height = (25 *4) + 2;
btnMenuGroup1.Image = Properties.Resources.up;
}
else
{
pnlMenuGroup1.Height = 25;
btnMenuGroup1.Image = Properties.Resources.down;
}
}
private void btnMenuGroup2_Click(object sender, EventArgs e)
{
if (pnlMenuGroup2.Height == 25)
{
pnlMenuGroup2.Height = (25 * 4) + 2;
btnMenuGroup2.Image = Properties.Resources.up;
}
else
{
pnlMenuGroup2.Height = 25;
btnMenuGroup2.Image = Properties.Resources.down;
}
}
private void btnMenuGroup3_Click(object sender, EventArgs e)
{
if (pnlMenuGroup3.Height == 25)
{
pnlMenuGroup3.Height = (25 * 4) + 2;
btnMenuGroup3.Image = Properties.Resources.up;
}
else
{
pnlMenuGroup3.Height = 25;
btnMenuGroup3.Image = Properties.Resources.down;
}
}
private void btnAbout_Click(object sender, EventArgs e)
{
frmAbout frmChild = new frmAbout();
frmChild.MdiParent = this;
frmChild.Show();
}
}
}
For details, download the project sample attached.
Enjoy programming!