2013-01-11 51 views
0

我需要從我的網頁動態地設置任何類型控件(例如文本框,標籤,HyperLink..etc)的文本屬性。這裏是我的代碼如何從網頁動態設置任何類型的網頁控件的文本屬性

foreach (string id in List<IdCollection>) 
{ 
Control ctrl = (this.Page.FindControl(id)); // Control should be HtmlGenericControl or WebControl. 
ctrl.Text=???(This property is not available for Control Class).. 
} 

我不需要檢查組文本屬性的每一個控制型像如下代碼

if(ctrl is TextBox) 
{ 
((TextBox)ctrl).Text="test"; 
} 

if(ctrl.GetType()==typeof(TextBox)) 
{ 
((TextBox)ctrl).Text="test"; 
} 

是否有任何其他設置文本屬性的方法很簡單,就像 以下代碼

WebControl wbCntrl=(WebControl)ctrl; 
wbCntrl.Tooltip="tooltip"; //// This is possible 
wbCntrl.Text="test" ??? //// But this is not possible 

感謝

回答

0

如果您正在使用C#4.0(VS 2010),那麼你可以使用 「動態」 的文章:

foreach (string id in List<IdCollection>) 
{ 
    dynamic ctrl = (this.Page.FindControl(id)); 
    ctrl.Text = "test"; 
} 

顯然,如果你嘗試,你會得到一個運行時異常在缺少Text屬性的控件上執行此操作。

+0

謝謝托馬斯..但即時通訊使用C#3.5。所以'動態'不支持Text屬性。 – Suresh

相關問題