递归查找页面控件并添加属性

本文关键字:添加 属性 控件 查找 递归 | 更新日期: 2023-09-27 17:48:55

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

递归查找页面控件并添加属性

这应该有效:

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