0% found this document useful (0 votes)
26 views1 page

Create UserControl Dynamic

The document presents a C# class 'Form1' that manages dynamic loading and displaying of UserControls in a Windows Forms application. It utilizes reflection to find and instantiate UserControls based on their names, adding them to a dictionary for easy access. If a UserControl is already loaded, it brings it to the front; otherwise, it creates a new instance and adds it to the form's controls.

Uploaded by

peyman sharifi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views1 page

Create UserControl Dynamic

The document presents a C# class 'Form1' that manages dynamic loading and displaying of UserControls in a Windows Forms application. It utilizes reflection to find and instantiate UserControls based on their names, adding them to a dictionary for easy access. If a UserControl is already loaded, it brings it to the front; otherwise, it creates a new instance and adds it to the form's controls.

Uploaded by

peyman sharifi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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);
}
}
}
}

You might also like