Sandeep's answer works. But the user control should be an instance and also remove previous control in the panel.
For example
private void button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new UserControl1());
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new UserControl2());
}
Alternatively....
Use hide and show as below
public partial class Form1 : Form
{
private UserControl1 ctrl1;
private UserControl2 ctrl2;
public Form1()
{
InitializeComponent();
}
private void toggleUserCtrl(object sender, EventArgs e)
{
if (sender.Equals(button1))
{
ctrl1.Visible = true;
ctrl2.Visible = false;
}else if(sender.Equals(button2)){
ctrl1.Visible = false;
ctrl2.Visible = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ctrl1 = new UserControl1();
ctrl2 = new UserControl2();
panel1.Controls.Add(ctrl1);
panel1.Controls.Add(ctrl2);
ctrl1.Visible = true;
ctrl2.Visible = false;
button1.Click += new EventHandler(toggleUserCtrl);
button2.Click += new EventHandler(toggleUserCtrl);
}
}