2012-08-23 45 views
1

我加载动态指定用户控制到一个占位符在这样的父(用户)控制:将用户控件从类型名称转换为自定义控件类型?

// dynamically load instance of chosen chart control 
string chartClassName = ConfigurationManager.AppSettings["ChartControlClass"]; 
_chartControl = (IOutputChart)LoadControl(chartClassName + ".ascx"); 
// add to place-holder 
if (chartClassName == "OutputChart_Dundas") phChart.Controls.Add((OutputChart_Dundas)_chartControl); 
else if (chartClassName == "OutputChart_Microsoft") phChart.Controls.Add((OutputChart_Microsoft)_chartControl); 
else if (chartClassName == "OutputChart_Telerik") phChart.Controls.Add((OutputChart_Telerik)_chartControl); 

显然,这将是更好不具有对_chartControl变量每次显式转换 - 有更清洁的方式吗?每个用户控件都实现了IOutputChart接口;然而,我不能直接使用它,因为Controls.Add()需要一个Control对象。

回答

3

你能不能把所有这些转换成Control

phChart.Controls.Add((Control)_chartControl); 
+0

啊 - 很明显是的,我可以,所以谢谢你<嘲笑的笑容>。我曾试图转换为* WebControl *,认为这会起作用,但得到了运行时错误“无法将类型为'ASP.controls_outputchart_dundas_ascx'的对象转换为键入'System.Web.UI.WebControls.WebControl'”。 - 我没有想到“控制”会起作用,而“WebControl”不会。无论如何,非常感谢您的支持 - 非常感谢。 –

2

我假设你所有的控件都是从基类Control派生的。那你为什么不把_chartControl转换成Control并添加它。

_chartControl = (Control)LoadControl(chartClassName + ".ascx"); 
phChart.Controls.Add(_chartControl); 
+0

的确如此 - 非常感谢(上面的评论为我的明显缺乏努力的解释第一次)!不过,我实际上需要_chartControl变量作为IOutputChart对象。 –

+0

没问题。即使_chartControl的类型是Control,您仍然可以使用_chartControl作为IOutputChart对象。 – daryal

相关问题