我加载动态指定用户控制到一个占位符在这样的父(用户)控制:将用户控件从类型名称转换为自定义控件类型?
// 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
对象。
啊 - 很明显是的,我可以,所以谢谢你<嘲笑的笑容>。我曾试图转换为* WebControl *,认为这会起作用,但得到了运行时错误“无法将类型为'ASP.controls_outputchart_dundas_ascx'的对象转换为键入'System.Web.UI.WebControls.WebControl'”。 - 我没有想到“控制”会起作用,而“WebControl”不会。无论如何,非常感谢您的支持 - 非常感谢。 –