我需要一个递归函数,它可以找到页面上的所有控件,并允许我根据控件类型添加javascript控件属性。
问题是我有一个页面,其中有几个面板有控件。面板甚至可以嵌套面板/控件。
不幸的是,以下内容没有达到我想要的效果,但我正在寻找类似的东西......
Action<Control> traverse = null;
//in a function:
traverse = (ctrl) =>
{
//ctrl.Enabled = false; //or whatever action you're performing
foreach (Control c in ctrl.Controls)
{
Response.Write(c.GetType().ToString() + " : " + c.ID.ToString() + "<br />");
if (c.GetType() == typeof(TextBox))
{
((TextBox)(c)).Attributes["onKeypress"] = "javascript:return FormEdited();";
}
else if (c.GetType() == typeof(DropDownList))
{
((DropDownList)(c)).Attributes["onchange"] = "javascript:return FormEdited();";
}
else if (c.GetType() == typeof(CheckBox))
{
((CheckBox)(c)).Attributes["onClick"] = "javascript:return FormEdited();";
}
}
traverse = (ctrl2) => ctrl.Controls.GetEnumerator();
};
答案 0 :(得分:2)
这应该有效:
public void traverse(Control ctl)
{
foreach (Control c in ctl.Controls)
{
System.Diagnostics.Debug.WriteLine(c.GetType().ToString());
//Response.Write(c.GetType().ToString() + " : " + c.ID.ToString() + "<br />");
if (c.GetType() == typeof(TextBox))
{ ((TextBox)(c)).Attributes["onKeypress"] = "javascript:return FormEdited();";
}
if (c.GetType() == typeof(DropDownList))
{ ((DropDownList)(c)).Attributes["onchange"] = "javascript:return FormEdited();";
}
else if (c.GetType() == typeof(CheckBox))
{ ((CheckBox)(c)).Attributes["onClick"] = "javascript:return FormEdited();";
}
traverse(c);
}
}
然后用:
调用它traverse(this.Page);
即
protected void Page_Load(object sender, EventArgs e)
{
traverse(this.Page);
}