C#LoadControl()(。ascx)并添加到“this”而不是子控件

时间:2012-06-07 10:50:30

标签: c# asp.net ascx

我很擅长使用LoadControl("~/vitrualPath")加载控件,所以我有:

UserControl ctrl = (UserControl)LoadControl("~/controls/someControl.ascx");
this.Controls.Add(ctrl);
//plcCtrl.Controls.Add(ctrl);

麻烦的是我希望循环遍历usercontrol中的所有控件:

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

5 个答案:

答案 0 :(得分:2)

如果您只想浏览ctrl中的顶级标签和标签,请在this.Controls.Concat(ctrl.Controls).OfType<Label>()循环中尝试foreach

您还可以将if移至LINQ Where来电:

.Where(l => l.ID.Substring(0, 8) == "lblInput")

答案 1 :(得分:1)

通过使用递归函数,您不必担心子级/容器内的控件。这样的事情应该没问题(你需要做的就是将顶级控件和你感兴趣的id子字符串一起传递)。因此,如果满足条件,它将执行您对控件以及任何子级别的意图。

public void ProcessControl(Control control, string ctrlName)
{
    foreach (Label c in control.Controls.OfType<Label>())
   {
       // It's a label for an input
       if (c.ID.Substring(0, 8) == ctrlName)
       {
            // Do some stuff with the control here
       }
    }

    foreach (Control ctrl in control.Controls)
    {
        ProcessControl(ctrl, ctrlName);        
    }    
}

答案 2 :(得分:0)

你应该编写一个递归方法,开始循环this.Controls中的控件并沿着控件树向下移动。然后它也会进入您的用户控件并找到您的标签。

答案 3 :(得分:0)

我认为没有办法像你想要的那样循环使用。

您可以轻松创建一个接收Control as参数并迭代其控件的方法。像这样:

void Function(Control control)
{
    foreach (Label c in control.Controls.OfType<Label>())
    {
       // It's a label for an input
       if (c.ID.Substring(0, 8) == "lblInput")
       {
         // Do some stuff with the control here
       }
    }
}

答案 4 :(得分:0)

您应该能够通过访问this.Controls[index].Controls来访问用户控件中的控件,但这取决于您要实现的目标?他们可能是一种更干净的方式来做你想做的事情?

相关问题