2012-07-12 32 views
14

我能得到一個頁面的所有控件以及它們的類型的ID,在頁面當我打印出來它顯示檢查控制型

myPhoneExtTxt Type:System.Web.UI.HtmlControls.HtmlInputText 

這是生成基於此代碼

foreach (Control c in page) 
    { 
     if (c.ID != null) 
     { 
      controlList.Add(c.ID +" Type:"+ c.GetType()); 
     } 
    } 

但現在我需要檢查它的類型,如果它的類型HtmlInput的訪問它的文字和我不太知道如何做到這一點。

if(c.GetType() == (some htmlInput)) 
{ 
    some htmlInput.Text = "This should be the new text"; 
} 

我怎麼能做到這一點,我覺得你的想法?

回答

31

這應該是你所需要的,如果我得到你的要求:

if (c is TextBox) 
{ 
    ((TextBox)c).Text = "This should be the new text"; 
} 

如果你的主要目標是隻設置一些文字:

if (c is ITextControl) 
{ 
    ((ITextControl)c).Text = "This should be the new text"; 
} 

爲了支持隱藏字段以及:

string someTextToSet = "this should be the new text"; 
if (c is ITextControl) 
{ 
    ((ITextControl)c).Text = someTextToSet; 
} 
else if (c is HtmlInputControl) 
{ 
    ((HtmlInputControl)c).Value = someTextToSet; 
} 
else if (c is HiddenField) 
{ 
    ((HiddenField)c).Value = someTextToSet; 
} 

必須將其他控件/接口添加到邏輯中。

+0

這是否包括輸入類型是否隱藏? – user1416156 2012-07-12 19:28:18

+0

不幸的是,沒有。 HiddenFields是討厭的小混蛋,因爲它們不會從許多有用的東西中繼承,必須直接進行解釋。我編輯了我的答案以包含支持。 – 2012-07-12 19:33:07

+0

也可以考慮在類型檢查中使用'as'運算符。 – 2015-05-21 06:12:04