Run-Time creation and siting of UserControls
1. key elements
a. create the instance:
UserControl1 myUC1 = new UserControl1();
b. add the instance to a Form or other ContainerControl's ControlCollection:
form1.Controls.Add(myUC1);
c. set the location and/or z-order of the added UserControl:
myUC1.Location = new Point(200,200);<br />
myUC1.BringToFront();
If you really want to destroy/clear an existing UserControl to make sure each time you create the UserControl at run-time you have a "fresh" instance:
UserControl1 myUC1;
private void button1_Click(object sender, EventArgs e)
{
if(myUC1 != null) myUC1.Dispose();
if(myUC2 != null) myUC2.Dispose();
myUC1 = new UserControl1();
Controls.Add(myUC1);
myUC1.BringToFront();
}
UserControl2 myUC2;
private void button2_Click(object sender, EventArgs e)
{
if(myUC1 != null) myUC1.Dispose();
if(myUC2 != null) myUC2.Dispose();
myUC2 = new UserControl2();
Controls.Add(myUC2);
myUC2.BringToFront();
}
Re-using Design-Time sited UserControls
I suggest you create both UserControls
at design-time by drag-dropping them from the ToolBox onto the Form you wish them to appear on. You will need to compile your project once before they will appear in the ToolBox.
Position them where you want them to appear at run-time.
Then, for both UserControls, set their 'Visible property to 'false in their Properties Window. That way, initially they will not be visible.
So: in your code for the Buttons Click Event:
private void btnShowUC1_Click(object sender, EventArgs e)
{
userControl21.Hide();
userControl11.Show();
userControl11.BringToFront();
}
private void btnShowUC2_Click(object sender, EventArgs e)
{
userControl11.Hide();
userControl21.Show();
userControl21.BringToFront();
}
The only "downside" I can see to re-using design-time created UserControls like this is when you need to clear any fields, or any user data entered into Controls in the UserControls , before you re-use them.
For example, if you had a UserControl with a TextBox, and a CheckBox (with the CheckBox 'ThreeState property set to 'true), you could call a method like this from the Form where the UserControl is sited:
public void Clear()
{
textBox1.Clear();
checkBox1.CheckState = CheckState.Indeterminate;
}
Or, you could define an EventHandler for the 'VisibleChanged event of the UserControls, and, when the UserControl became visible, then clear field, re-set Controls, etc.
Since what one may wish to do when a Form, or UserControl is shown may vary, and may include wanting to show initial values, how you will handle fields and Controls as you re-use them will vary.
You could change the 'Clear example shown here, and, instead of clearing, reset whatever to pre-defined states, or values.