I want to know if it's possible to dynamically load user controls?
This is some code to show what I mean:
public void Load()
{
Reset();
if (_host.User == null)
return;
int _count = 0;
String[] _applications = _host.User.Applications;
if (_applications == null)
return;
foreach (String _application in _applications)
{
TabPage _page = null;
switch (_application)
{
case "SF01":
_page = new TabPage();
_page.Text = "SF01";
_page.Controls.Add(new SF01(_container));
break;
}
if (_page != null)
{
tapplications.TabPages.Add(_page);
m_list.Add(_count, _page);
_count++;
}
}
tapplications.TabPages.Add(tlog);
if (_host.User.Admin)
tapplications.TabPages.Add(tadmin);
_container.Controls.Add(this);
}
As you can see SF01 is my usercontrol.
Now how do I go about loading other usercontrols
by name instead of hard typing the class object?
This way I can create more applications and forget about how to load them. (case "SF01":)
All the applications will reside beneath a project folder applications, maybe there is a way to iterate through that project folder?
解决方案
Yes it is.
A User Control can be instanciated using Activator.CreateInstance, as any other kind of object.
string objTypeName = "myNamespace.UI.SF01"; // Full namespace name
SF01 myNewSF01 = (Foo)Activator.CreateInstance(Type.GetType(objTypeName));
Then you can replace your switch statement with
_page = new TabPage();
_page.Text = "SF01";
var control = (Control)Activator.CreateInstance(Type.GetType("myNamespace." + _application));
_page.Controls.Add(control);