查找以某个字符串开头的页面控件
Finding page controls starting with some string
我在 ASP.NET 页面中有很多 TextBox
,它们的 ID
以特定字符串开头,例如 xyz
(例如:xyz1
,xyz11
,xyz999
).我知道 FindControl
方法,但它只能通过 Control
的完整 ID
找到。
如何找到 ID
与页面上的控件相同的控件?
您必须在页面内递归循环以找到与您的字符串匹配的 TextBox 控件:
List<TextBox> _TextBoxes;
protected void Page_Load(object sender, EventArgs e)
{
_TextBoxes = new List<TextBox>();
FindTextBoxes(Page, "xyz1");
}
private void FindTextBoxes(Control parent, string startsWith)
{
if(parent.GetType()==typeof(TextBox) && parent.ID.StartsWith(startsWith))
{
_TextBoxes.Add(parent as TextBox);
}
foreach (var c in parent.Controls)
{
FindTextBoxes(c, startsWith);
}
}
您可以包含 Extension Method
以获取 this answer 中提到的页面上的所有文本框,然后可以像这样简单地使用您需要的 ID 进行过滤:-
var alltextBoxes = this.Page.FindControls<TextBox>(true).Where(x => x.ID.Contains("xyz"));
如果您想要所有以某些特定文本开头的 ID,比如 xyz
,那么您也可以使用 String.StartsWith,因为文本框 ID 是一个字符串:-
.Where(x => x.ID.StartsWith("xyz"));
我在 ASP.NET 页面中有很多 TextBox
,它们的 ID
以特定字符串开头,例如 xyz
(例如:xyz1
,xyz11
,xyz999
).我知道 FindControl
方法,但它只能通过 Control
的完整 ID
找到。
如何找到 ID
与页面上的控件相同的控件?
您必须在页面内递归循环以找到与您的字符串匹配的 TextBox 控件:
List<TextBox> _TextBoxes;
protected void Page_Load(object sender, EventArgs e)
{
_TextBoxes = new List<TextBox>();
FindTextBoxes(Page, "xyz1");
}
private void FindTextBoxes(Control parent, string startsWith)
{
if(parent.GetType()==typeof(TextBox) && parent.ID.StartsWith(startsWith))
{
_TextBoxes.Add(parent as TextBox);
}
foreach (var c in parent.Controls)
{
FindTextBoxes(c, startsWith);
}
}
您可以包含 Extension Method
以获取 this answer 中提到的页面上的所有文本框,然后可以像这样简单地使用您需要的 ID 进行过滤:-
var alltextBoxes = this.Page.FindControls<TextBox>(true).Where(x => x.ID.Contains("xyz"));
如果您想要所有以某些特定文本开头的 ID,比如 xyz
,那么您也可以使用 String.StartsWith,因为文本框 ID 是一个字符串:-
.Where(x => x.ID.StartsWith("xyz"));