通过asp.net中的TextBoxes进行迭代 – 为什么这不起作用?

我有两种方法试图迭代asp.net页面中的所有文本框。 第一个是工作,但第二个没有返回任何东西。 有人可以向我解释为什么第二个不起作用?

这样可行:

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

和“不工作”代码:

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

您的第一个示例是执行一个级别的递归,因此您将获得控件树中多个控件深的TextBox。 第二个示例仅获取顶级TextBox(您可能很少或没有)。

这里的关键是Controls集合不是页面上的每个控件 – 而是它只是当前控件的直接子控件 (而Page是一种Control )。 这些控制可能反过来又有自己的控制。 要了解有关此内容的更多信息,请在此处阅读有关ASP.NET控制树以及有关NamingContainers的信息 。 要真正获得页面上任何位置的每个TextBox,您需要一个递归方法,如下所示:

 public static IEnumerable FindControls(this Control control, bool recurse) where T : Control { List found = new List(); Action 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(true); 

你需要递归。 控件采用树形结构 – Page.Controls不是页面上所有控件的展平列表。 您需要执行以下操作以获取TextBoxes的所有值:

 void GetTextBoxValues(Control c, List strings) { TextBox t = c as TextBox; if (t != null) strings.Add(t.Text); foreach(Control child in c.Controls) GetTextBoxValues(child, strings); } 

 List strings = new List(); GetTextBoxValues(Page, strings); 

你可以尝试这段代码来获取所有TextBox的列表

 public partial class _Default : System.Web.UI.Page { public List ListOfTextBoxes = new List(); protected void Page_Load(object sender, EventArgs e) { // after execution this line FindTextBoxes(Page, ListOfTextBoxes); //ListOfTextBoxes will be populated with all text boxes with in the page. } private void FindTextBoxes(Control Parent, List ListOfTextBoxes) { foreach (Control c in Parent.Controls) { // if c is a parent control like panel if (c.HasControls()) { // search all control inside the panel FindTextBoxes(c, ListOfTextBoxes); } else { if (c is TextBox) { // if c is type of textbox then put it into the list ListOfTextBoxes.Add(c as TextBox); } } } } }