Iterating through TextBoxes in asp.net - why is this not working?(遍历 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 集合并不是页面上的每个控件 - 相反,它只是当前控件的 直接子控件(以及一个 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 - 为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:遍历 asp.net 中的 TextBoxes - 为什么这不起作用?
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
