using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
public class Form1 : Form
{
private Dictionary<string, UserControl> userControls = new Dictionary<string,
UserControl>();
public void ShowUserControl(string controlName)
{
if (userControls.ContainsKey(controlName))
{
// If the control already exists, bring it to the front
userControls[controlName].BringToFront();
}
else
{
// Use reflection to find the UserControl type in the current assembly
Type controlType = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == controlName
&& t.IsSubclassOf(typeof(UserControl)));
if (controlType != null)
{
// Create an instance dynamically
UserControl newControl =
(UserControl)Activator.CreateInstance(controlType);
newControl.Name = controlName;
userControls[controlName] = newControl;
newControl.Dock = DockStyle.Fill; // Optional: Adjust layout
this.Controls.Add(newControl);
newControl.BringToFront();
}
else
{
MessageBox.Show($"UserControl '{controlName}' not found in the
solution!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}