简体   繁体   English

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

[英]Recursively find page controls and add attributes?

I need a recursive function that will find all controls on a page and allow me to add javascript control attributes based on the control type. 我需要一个递归函数,它将在页面上找到所有控件,并允许我根据控件类型添加javascript控件属性。

The issue is that I have a page with several panels which have controls. 问题是我有一个页面,其中有几个面板有控件。 The panels could even have nested panels/controls. 面板甚至可以有嵌套的面板/控件。

Unfortunately the following doesn't do what I want, but I'm looking for something similar.... 不幸的是,以下没有做我想要的,但我正在寻找类似的东西....

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

This should work: 这应该工作:

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

and then call it with: 然后用以下方法调用它:

traverse(this.Page);

ie

protected void Page_Load(object sender, EventArgs e)
{
   traverse(this.Page);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM