0

我需要一个递归函数来查找页面上的所有控件,并允许我根据控件类型添加 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();
                };
4

1 回答 1

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);

IE

protected void Page_Load(object sender, EventArgs e)
{
   traverse(this.Page);
}
于 2011-04-06T16:04:39.413 回答