代码之家  ›  专栏  ›  技术社区  ›  MAW74656

循环浏览asp.net网页上的所有控件

  •  6
  • MAW74656  · 技术社区  · 14 年前

    我需要循环浏览我的asp.net网页中的所有控件,并对该控件执行某些操作。在一个例子中,我在页面中创建一个巨大的字符串,并将其发送给自己;在另一个例子中,我将所有内容保存到一个cookie中。

    问题是母版页和包含控件集合的项。我希望能够将一个页面传递给该方法,然后使该方法具有足够的泛型,能够遍历最内部内容页中的所有控件并与它们一起工作。我试过用递归做这个,但是我的递归是不完整的。

    我想将一个页面对象传递到一个方法中,并让该方法循环遍历最里面的内容页中的所有控件。我怎样才能做到这一点?

        private static String controlToString(Control control)
    {
        StringBuilder result = new StringBuilder();
    
        String controlID = String.Empty;
    
        Type type = null;
    
        foreach (Control c in control.Controls)
        {
            try
            {
                controlID = c.ID.ToString();
    
                if (c is IEditableTextControl)
                {
                    result.Append(controlID + ": " + ((IEditableTextControl)c).Text);
                    result.Append("<br />");
                }
                else if (c is ICheckBoxControl)
                {
                    result.Append(controlID + ": " + ((ICheckBoxControl)c).Checked);
                    result.Append("<br />");
                }
                else if (c is ListControl)
                {
                    result.Append(controlID + ": " + ((ListControl)c).SelectedValue);
                    result.Append("<br />");
                }
                else if (c.HasControls())
                {
                    result.Append(controlToString(c));
                }
    
                //result.Append("<br />");
            }
            catch (Exception e)
            {
    
            }
        }
    
        return result.ToString();
    }
    

    没有尝试/捕捉

    对象引用未设置为对象的实例。

    联机控制ID=。。。。。

    6 回复  |  直到 14 年前
        1
  •  8
  •   assylias    13 年前

    如果从文档的根元素开始,则原始方法将不起作用:例如page.Controls,因为您将只循环第一级控件,但请记住,控件可以是复合控件。所以你需要递归来实现它。

            public void FindTheControls(List<Control> foundSofar, Control parent) 
            {
    
                foreach(var c in parent.Controls) 
                {
                      if(c is IControl) //Or whatever that is you checking for 
                      {
    
                          foundSofar.Add(c);
    
                          if(c.Controls.Count > 0) 
                          {
                                this.FindTheControls(foundSofar, c);
                          }
                      }
    
    
                }  
    
            }
    
        2
  •  25
  •   Daniel Powell    13 年前

    我更喜欢David Finleys linq的FindControl方法 http://weblogs.asp.net/dfindley/archive/2007/06/29/linq-the-uber-findcontrol.aspx

    public static class PageExtensions
    {
        public static IEnumerable<Control> All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (Control grandChild in control.Controls.All())
                    yield return grandChild;
    
                yield return control;
            }
        }
    }
    

    用法:

    // get the first empty textbox
    TextBox firstEmpty = accountDetails.Controls
        .All()
        .OfType<TextBox>()
        .Where(tb => tb.Text.Trim().Length == 0)
        .FirstOrDefault();
    
    // and focus it
    if (firstEmpty != null)
        firstEmpty.Focus();
    
        3
  •  2
  •   Bob    13 年前
    foreach (Control ctlMaster in Page.Controls)
    {
        if (ctlMaster is MasterPage)
        {
            foreach (Control ctlForm in ctlMaster.Controls)
            {
                if (ctlForm is HtmlForm)
                {
                    foreach (Control ctlContent in ctlForm.Controls)
                    {
                        if (ctlContent is ContentPlaceHolder)
                        {
                            foreach (Control ctlChild in ctlContent.Controls)
                            {
                                //Do something!
                            }
                        }
                    }
                }
            }
        }
    }
    

    这样就可以了。不过,如果有多个内容占位符,您可能需要进行一些检查以确保实际处理的是正确的内容占位符。

        4
  •  0
  •   Ali Tarhini    14 年前
    sub getcontrols(byref c as control, byref allControls as list(of control)
    if c isnot nothing
    allcontrols.add(c)
    if c.controls.count>0 then
    for each ctrl as control in c.controls
    getcontrols(ctrl,allcontrols)
    next
    end if
    
        5
  •  0
  •   Fandango68    9 年前

    这对我很管用。。

    只需确保所有控件都以下面显示的前缀开头。即: <asp:TextBox ID="TextBoxEmail"...> 例如。否则解析器将检测不到您的控件。如果有人在不知道/硬编码控件ID的情况下有更好的解析方法,那就更贴心了。

    protected String GetControls(Control control)
    {
        //Get text from form elements
        String text = "";
        foreach (Control ctrl in control.Controls)
        {
            if (ctrl.ClientID.Contains("TextBox"))
            {
                TextBox tb = (TextBox)ctrl;
                text += tb.ID.Replace("TextBox", "") + ": " + tb.Text + "<br />";
            }
            if (ctrl.ClientID.Contains("RadioButtonList"))
            {
                RadioButtonList rbl = (RadioButtonList)ctrl;
                text += rbl.ID.Replace("RadioButtonList", "") + ": " + rbl.SelectedItem.Text + "<br />";
            }
            if (ctrl.ClientID.Contains("DropDownList"))
            {
                DropDownList ddl = (DropDownList)ctrl;
                text += ddl.ID.Replace("DropDownList", "") + ": " + ddl.SelectedItem.Text + "<br />";
            }
    
            if (ctrl.ClientID.Contains("CheckBox"))
            {
                CheckBox cb1 = (CheckBox)ctrl;
                text += cb1.ID.Replace("CheckBox", "") + ": " + cb1.Text + "<br />";
            }
    
            if (ctrl.HasControls())
                text += GetControls(ctrl);
        }
    
        return text;
    }
    

    调用它,传递页面对象。。。

    String log;
    foreach (Control ctrl in Page.Controls)
        log += GetControls(ctrl);
    
        6
  •  0
  •   Jagadheesh Venkatesan    9 年前

    请查找以下代码。这将帮助您完成所有需要的控制。您应该能够使用网页控件以及ASP.NET控件。

    public partial class Default : System.Web.UI.Page
    {
    
    List<Control> lstControl = new List<Control>();
    
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    
    private List<Label> getLabels() // Add all Lables to a list
    {
        List<Label> lLabels = new List<Label>();
    
        foreach (Control oControl in Page.Controls)
        {
            GetAllControlsInWebPage(oControl);
        }
    
        foreach (Control oControl in lstControl)
        {
            if (oControl.GetType() == typeof(Label))
            {
                lLabels.Add((Label)oControl);
            }
        }
        return lLabels;
    }
    
    protected void GetAllControlsInWebPage(Control oControl)
    {
        foreach (Control childControl in oControl.Controls)
        {
            lstControl.Add(childControl); //lstControl - Global variable
            if (childControl.HasControls())
                GetAllControlsInWebPage(childControl);
        }
    }
    
    }