循环遍历asp.net网页上的所有控件

发布于 2024-10-04 05:02:43 字数 1542 浏览 3 评论 0原文

我需要循环遍历我的 asp.net 网页中的所有控件并对控件执行一些操作。在一种情况下,我从页面中制作了一个巨大的字符串,并将其通过电子邮件发送给自己,而在另一种情况下,我将所有内容保存到 cookie 中。

问题在于母版页和其中包含控件集合的项目。我希望能够将 Page 传递给该方法,然后让该方法足够通用,以便循环遍历最内部内容页面中的所有控件并使用它们。我尝试过用递归来做到这一点,但我的递归不完整。

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

    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 = .....

I need to loop through all the controls in my asp.net webpage and do something to the control. In one instance I'm making a giant string out of the page and emailing it to myself, and in another case I'm saving everything to a cookie.

The problem is masterpages and items with collections of controls inside them. I want to be able to pass in a Page to the method, then have that method be generic enough to loop through all controls in the inner-most content page and work with them. I've tried doing this with recursion, but my recursion is incomplete.

I want to pass a Page object into a method, and have that method loop through all controls in the innermost content page. How can I achieve this?

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

Without Try/catch

Object reference not set to an instance of an object.

On line controlID = .....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

红焚 2024-10-11 05:02:43

我更喜欢 David Finley 的 FindControl linq 方法 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();

I rather like David Finleys linq approach to 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;
        }
    }
}

Usage:

// 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();
柠檬心 2024-10-11 05:02:43

如果您从文档的根元素开始,您原来的方法将不起作用:类似于 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);
                      }
                  }


            }  

        }

Your original method will not work if you start from the root element of your document: something like page.Controls as you will only loop through the first level of controls, but remember a control can be composite. So you need recursion to pull that off.

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


            }  

        }
可爱暴击 2024-10-11 05:02:43
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!
                        }
                    }
                }
            }
        }
    }
}

这应该可以做到。不过,如果有多个 ContentPlaceHolder,您可能需要进行一些检查以确保您实际上正在处理正确的 ContentPlaceHolder。

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!
                        }
                    }
                }
            }
        }
    }
}

This should do it. Though you might need to do some checking to make sure you're actually dealing with the correct ContentPlaceHolder if there's more than one.

赴月观长安 2024-10-11 05:02:43
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
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
寒江雪… 2024-10-11 05:02:43

这对我有用..

只需确保您识别所有以下面所示的前缀开头的控件。例如:。否则解析器将无法检测到您的控件。如果有人有更好的方法在不知道/硬编码控件 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;
}

并传递 Page 对象来调用它......

String log;
foreach (Control ctrl in Page.Controls)
    log += GetControls(ctrl);

This worked for me ..

Just make sure you ID all your controls starting with the prefixes shown below. ie: <asp:TextBox ID="TextBoxEmail"...> for example. Otherwise the parser will not detect your control. If someone has a better way of parsing without knowing / hard-coding the ID of the controls, that would be even sweeter.

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

And to call it, passing Page object ...

String log;
foreach (Control ctrl in Page.Controls)
    log += GetControls(ctrl);
檐上三寸雪 2024-10-11 05:02:43

请找到下面的代码。这应该可以帮助您完成所需的所有控制。您应该能够使用网页控件以及 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);
    }
}

}

Please find the below code. This should help you with all the controls you need. You should be able to use Web Page Controls, as well as ASP.NET Controls.

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

}
挽你眉间 2024-10-11 05:02:43

尽管这个问题已经讨论了 9 年多了,但在这里我留下了基于 @Jagadheesh Venkatesan 的代码对我有用的代码。

private List<Control> getControls()
{
    List<Control> lControls = new List<Control>();
    foreach (Control oControl in Page.Controls)
        foreach (Control childControl1 in oControl.Controls)
            foreach (Control childControl2 in childControl1.Controls)
                foreach (Control childControl3 in childControl2.Controls)
                    if (childControl3.GetType().ToString().Contains("System.Web.UI.WebControls"))
                        lControls.Add(childControl3);
    return lControls;
}

Even though this question has been discussed for more than 9 years, here I leave the code that worked for me based on @Jagadheesh Venkatesan's code.

private List<Control> getControls()
{
    List<Control> lControls = new List<Control>();
    foreach (Control oControl in Page.Controls)
        foreach (Control childControl1 in oControl.Controls)
            foreach (Control childControl2 in childControl1.Controls)
                foreach (Control childControl3 in childControl2.Controls)
                    if (childControl3.GetType().ToString().Contains("System.Web.UI.WebControls"))
                        lControls.Add(childControl3);
    return lControls;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文