我很擅长使用 LoadControl("~/vitrualPath")
加载控件,所以我有:
UserControl ctrl = (UserControl)LoadControl("~/controls/someControl.ascx");
this.Controls.Add(ctrl);
//plcCtrl.Controls.Add(ctrl);
问题是我希望循环遍历用户控件中的所有控件:
foreach (Label c in this.Controls.OfType<Label>())
{
// It's a label for an input
if (c.ID.Substring(0, 8) == "lblInput")
{
// Do some stuff with the control here
}
}
但是,添加的控件不是 this
的一部分,而是 ctrl
的一部分
有没有一种方法可以将加载的控件的内容添加到 this
或循环遍历 this
和 ctrl
一击?
最佳答案
如果您只想循环遍历顶级标签和 ctrl
中的标签,尝试this.Controls.Concat(ctrl.Controls).OfType<Label>()
在你的foreach
循环。
您还可以移动您的if
进入 LINQ Where
调用:
.Where(l => l.ID.Substring(0, 8) == "lblInput")
关于C# LoadControl() (.ascx) 并添加到 "this"而不是子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10930314/