2012-08-23 42 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

相關問題