Place your UserControls within the user controls panel. They don't need to sit anywhere special, just so you reach any of them in design mode in case you want to change something.
When starting your application, tell each of them to cover the whole user controls panel, but at the same time go invisible.
public class Form1
{
protected override OnLoad( object sender, EventArgs e)
{
foreach( Control control in userControlsPanel.Controls)
{
control.Dock = DockStyle.Fill;
control.Visible = false;
}
}
}
Then create event handler methods for your buttons. One of them could look like this
public class Form1
{
private void Button1_Click( object sender, EventArgs e)
{
foreach( Control control in userControlPanel.Controls)
{
control.Visible = AreAssociated( Button1, control);
}
}
}
There are several ways how you could associate a button with one of the user controls.
You could use the button's
Tag
property in such a way:
Button1.Tag = UserControl1;
Above code would then change to
control.Visible = ( control.Equals(Button1.Tag));
Furthermore, it would be nicer not to have one event handler per button, but to have one event handler that handles all the
Click
events of the similarly used buttons. You can attach one event handler so several button click events. The handler could then look like
public class Form1
{
private void AnyButton_Click( object sender, EventArgs e)
{
if(!(sender is Button))
{
throw new ArgumentException("AnyButton_Click() has to be called by a Button.");
}
foreach( Control control in userControlPanel.Controls)
{
control.Visible = control.Equals((Button)sender).Tag;
}
}
}