如何通过父面板用户控件的id获取子用户控件?

时间:2012-07-31 06:10:58

标签: c# .net visual-studio

例如。我的代码是

void abc(usercontrolclass ucc)
{
   this.panel.Controls.Add(ucc);
}

void def()
{
  usercontrolclass ucc1 = this.panel.Controls.GetChildUserControl(ucc);

}

注意“GetChildUserControl”不是我需要的有效函数是方法或       我可以用来获取ucc的功能。

2 个答案:

答案 0 :(得分:2)

1 - 设置用户控件tag属性。

2 - 将用户控件添加到其父级。

3 - 通过迭代Control.Controls从父级获取Tag属性的用户控制权。

您的代码应该是这样的:

void AddControl(UserControl control, int id)
{
    control.Tag = id;
    this.panel.Controls.Add(control);
}

UserControl GetControl(int id)
{
    foreach (Control control in this.panel.Controls)
    {
        if (id == (int) control.Tag)
            return (UserControl) control;
    }
    return null;
}

// or using LINQ
UserControl GetControl(int id)
{
    return Controls.Cast<UserControl>()
                   .FirstOrDefault(control => id == (int) control.Tag);
}

答案 1 :(得分:0)

用户控件也只是一个控件,因此它具有带控件的Controls属性。使用它。

请参阅herehere