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 - 为什么这不起作用?
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
