[英]How can I get all TextBoxes inside of a Custom UserControl?
I need a way to dynamically gather all of the TextBoxes inside of a custom UserContorl in ASP.net WebForms, server-side 我需要一种在服务器端动态收集ASP.net WebForms中自定义UserContorl内的所有TextBox的方法
I thought this would work: 我认为这可以工作:
foreach (var control in Page.Controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
// stuff here
}
}
But it doesn't do what I thought it would, and I don't see how else to get that information. 但是它并没有达到我的预期,并且我也看不到如何获得这些信息。
So, how can I dynamically get all of the textboxes on the server-side of a custom UserControl in ASP.net webforms? 因此,如何在ASP.net Webforms中动态获取自定义UserControl的服务器端的所有文本框?
You need a recursive method, because not all level 1 children are necessarily text boxes (depends on the control/container hierarchy in your user control): 您需要一种递归方法,因为并非所有1级子级都必须是文本框(取决于用户控件中的控件/容器层次结构):
private IEnumerable<TextBox> FindControls(ControlCollection controls)
{
List<TextBox> results = new List<TextBox>();
foreach(var control in controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
results.Add(textBox);
}
else if(textBox == null)
{
results.AddRange(FindControls(control.Controls));
}
}
return results;
}
After you get the results you can iterate them and do whatever you need to do. 获得结果后,您可以迭代它们并执行所需的任何操作。
Looks like recursive is the way to go: 看起来递归是可行的方法:
foreach (Control control in Page.Controls)
{
DoSomething(control);
}
// And you need a new method to loop through the children
private void DoSomething(Control control)
{
if (control.HasControls())
{
foreach(Control c in control.Controls)
{
DoSomething(c);
}
}
else
{
var textBox = control as TextBox;
if (textBox != null)
{
// Do stuff here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.