C# LoadControl() (.ascx) 并添加到 "this"而不是子控件

标签 c# asp.net ascx

我很擅长使用 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 或循环遍历 thisctrl一击?

最佳答案

如果您只想循环遍历顶级标签和 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/

相关文章:

javascript - 如何获取Web浏览器的公钥(用于HTTPS)

c# - ascx 中的悬停表

css - 如何从不同的 .asxc 文件更改 CSS 背景?

c# - 无法在 .NET 4 的 IIS 中看到 .NET 用户

c# - 实现接口(interface) C#

c# - 如何计算每对字母的字距调整?

c# - OleDbConnection 获取 "External component has thrown an exception."

c# - 覆盖 ASP.NET MVC 事件样式表包

asp.net - 关闭浏览器实际上应该清除 session 变量和 ASP.net session ID

asp.net - ascx 中的内联动态字符串