问题描述
我有 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 集合并不是页面上的每个控件 - 相反,它只是当前控件的 直接子控件(以及一个 Page 是 Control 的一种).那些控件可能又拥有自己的子控件.要了解更多信息,请阅读 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 - 为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)