![](/img/trans.png)
[英]Why can't I access to a UserControl custom property inside a Repeater?
[英]How can I get all TextBoxes inside of a Custom UserControl?
我需要一種在服務器端動態收集ASP.net WebForms中自定義UserContorl內的所有TextBox的方法
我認為這可以工作:
foreach (var control in Page.Controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
// stuff here
}
}
但是它並沒有達到我的預期,並且我也看不到如何獲得這些信息。
因此,如何在ASP.net Webforms中動態獲取自定義UserControl的服務器端的所有文本框?
您需要一種遞歸方法,因為並非所有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;
}
獲得結果后,您可以迭代它們並執行所需的任何操作。
看起來遞歸是可行的方法:
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.