winform 读取用户控件的变量,C#Winform的动态加载用户控件的名字

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?

CRmP7.png

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值