C# 如何从父面板用户控件按id获取子用户控件?
例如,我的代码是C# 如何从父面板用户控件按id获取子用户控件?,c#,.net,visual-studio,C#,.net,Visual Studio,例如,我的代码是 void abc(usercontrolclass ucc) { this.panel.Controls.Add(ucc); } void def() { usercontrolclass ucc1 = this.panel.Controls.GetChildUserControl(ucc); } 注意“GetChildUserControl”不是一个有效的函数,我需要的是一个方法或 我可以用来获取ucc的函数。用户控件也是“只是”一个控件,所以它有一个带有子控
void abc(usercontrolclass ucc)
{
this.panel.Controls.Add(ucc);
}
void def()
{
usercontrolclass ucc1 = this.panel.Controls.GetChildUserControl(ucc);
}
注意“GetChildUserControl”不是一个有效的函数,我需要的是一个方法或
我可以用来获取ucc的函数。用户控件也是“只是”一个控件,所以它有一个带有子控件的Controls属性。使用它
请参阅和。1-设置用户控件
tag
属性
2-将用户控件添加到其父控件
3-通过迭代从父级通过其标记
属性获取用户控件
您的代码应该如下所示:
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);
}
void AddControl(UserControl控件,int-id)
{
control.Tag=id;
此.panel.Controls.Add(控件);
}
UserControl-GetControl(int-id)
{
foreach(此.panel.Controls中的控件)
{
if(id==(int)control.Tag)
返回(UserControl)控件;
}
返回null;
}
//或者使用LINQ
UserControl-GetControl(int-id)
{
返回控件.Cast()
.FirstOrDefault(control=>id==(int)control.Tag);
}
我不能在不循环每个控件的情况下执行此操作吗?