foreach(Label l in Controls) // setting all labels' s visbility on page to true
l.Visible =true;
但是在运行时,我遇到了以下错误:
无法将类型为“ASP.admin_master”的对象强制转换为类型“System.Web.UI.WebControls.Label”。
foreach(Label l in Controls.OfType<Label>())
{
l.Visible = true;
}
private void SetVisibility<T>(Control parent, bool isVisible)
{
foreach (Control ctrl in parent.Controls)
{
if(ctrl is T)
ctrl.Visible = isVisible;
SetVisibility<T>(ctrl, isVisible);
}
}
使用方法:
SetVisibility<Label>(Page, true);
检查当前的“l”是否具有所需的目标类型:
foreach(control l in Controls) {
if(l is System.Web.UI.WebControls.Label)
l.Visible = true;
}
foreach(Control l in Controls)
if (l is Label) l.Visible =true;
如果你想要在整个层次结构中:
public static void SetAllControls( Type t, Control parent /* can be Page */)
{
foreach (Control c in parent.Controls)
{
if (c.GetType() == t) c.Visible=true;
if (c.HasControls()) GetAllControls( t, c);
}
}
SetAllControls( typeof(Label), this);
controls =
。 - Magnuspublic void Search(Control control)
{
foreach (Control c in control.Controls)
{
if (c.Controls.Count > 0)
Search(c);
if (c is Label)
c.Visible = false;
}
}
和
Search(this.Page);
using System.Linq;
。除此之外,应该就没问题了。 - Karl-Johan Sjögren