2014-02-21 16 views
1

文字我有我的aspx頁面上的多個文字控件,它們都具有相同的值。這意味着,在我後面的代碼,我寫這10倍:指ASP:按類而不是ID

TheLiteral1.Text = "SameValue"; 
TheLiteral2.Text = "SameValue"; 

有沒有引用頁面,還是有辦法通過一個類名像CSS,以達到他們的所有文字的方式?

謝謝。

回答

2

您可以通過獲取控件集合在頁面上建立文字控件列表和按類型過濾他們,就像這樣:

using System.Web.UI.WebControls; 

List<Literal> literals = new List<Literal>(); 
foreach (Literal literal in this.Controls.OfType<Literal>()) 
{ 
    literals.Add(literal); 
} 

然後,您可以通過列表循環並將其值設置。

foreach (Literal literal in literals) 
{ 
    literal.Text = "MyText"; 
} 
1

要延長NWard的回答,你也可以寫,這將搜索指定類型的所有控件父控件的自定義方法。

public static void FindControlsByTypeRecursive(Control root, Type type, ref List<Control> list) 
{ 
    if (root.Controls.Count > 0) 
    { 
     foreach (Control ctrl in root.Controls) 
     { 
      if (ctrl.GetType() == type) //if this control is the same type as the one specified 
       list.Add(ctrl); //add the control into the list 
      if (ctrl.HasControls()) //if this control has any children 
       FindControlsByTypeRecursive(ctrl, type, ref list); //search children 
     } 
    } 
} 

利用這種高度可重複使用的方法,既可以搜索整個頁(通過this如在頁面的代碼隱藏的參數),或一個特定的容器等的數據綁定控件:)

+0

是的!這對Control集合的擴展方法特別有用,因此您可以調用List <[type]> controlList = this.Controls.FindByTypeRecursive(Type type),並讓它將調用代碼的控件及其子控件集作爲新列表返回。 – NWard

1

要建立在NWard的答案上,你可以通過使用Linq's進行篩選Where:

foreach (var literal in Controls.OfType<Literal>().Where(x => x.CssClass=="MyCSSClass") 
{ 
    literals.Add(literal); 
}