遍历 asp.net 中的 TextBoxes - 为什么这不起作用? [英] Iterating through TextBoxes in asp.net - why is this not working?

查看:13
本文介绍了遍历 asp.net 中的 TextBoxes - 为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 种方法尝试遍历 asp.net 页面中的所有文本框.第一个正在工作,但第二个没有返回任何东西.有人可以向我解释为什么第二个不起作用吗?

I have 2 methods I tried to iterate through all my textboxes in an asp.net page. The first is working, but the second one is not returning anything. Could someone please explain to me why the second one is not working?

这工作正常:

List<string> list = new List<string>();

    foreach (Control c in Page.Controls)
    {
        foreach (Control childc in c.Controls)
        {
            if (childc is TextBox)
            {
                list.Add(((TextBox)childc).Text);
            }
        }
    }

和不工作"的代码:

List<string> list = new List<string>();

    foreach (Control control in Controls)
    {
        TextBox textBox = control as TextBox;
        if (textBox != null)
        {
            list.Add(textBox.Text);
        }
    }

推荐答案

您的第一个示例是执行一级递归,因此您获得的 TextBoxes 在控件树的深处有多个控件.第二个示例仅获取顶级文本框(您可能很少或没有).

Your first example is doing one level of recursion, so you're getting TextBoxes that are more than one control deep in the control tree. The second example only gets top-level TextBoxes (which you likely have few or none).

这里的关键是 Controls 集合并不是页面上的每个控件 - 相反,它只是当前控件的 直接子控件(以及一个 PageControl 的一种).那些控件可能又拥有自己的子控件.要了解更多信息,请阅读 ASP.NET 控制树NamingContainers 在这里.要真正获取页面上任何位置的每个 TextBox,您需要一个递归方法,如下所示:

The key here is that the Controls collection is not every control on the page - rather, it is only the immediate child controls of the current control (and a Page is a type of Control). Those controls may in turn have child controls of their own. To learn more about this, read about the ASP.NET Control Tree here and about NamingContainers here. To truly get every TextBox anywhere on the page, you need a recursive method, like this:

public static IEnumerable<T> FindControls<T>(this Control control, bool recurse) where T : Control
{
    List<T> found = new List<T>();
    Action<Control> search = null;
    search = ctrl =>
        {
            foreach (Control child in ctrl.Controls)
            {
                if (typeof(T).IsAssignableFrom(child.GetType()))
                {
                    found.Add((T)child);
                }
                if (recurse)
                {
                    search(child);
                }
            }
        };
    search(control);
    return found;
}

用作扩展方法,如下所示:

var allTextBoxes = this.Page.FindControls<TextBox>(true);

这篇关于遍历 asp.net 中的 TextBoxes - 为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆