我有一个动态Label
Tag
创建了14 Label
并添加到GroupBox
,然后,我想搜索Label
有一个Tag = "ABC"
,我试过这个:
var items = grouptodayerror.ControlCollection;
var finditem = items.Cast<Control>().FirstOrDefault(control => String.Equals(control.Tag, "ABC");
grouptodayerror
是我的GroupBox
,收到错误消息
Error 1 'ControlCollection': cannot reference a type through an expression; try 'System.Windows.Forms.Control.ControlCollection' instead
我也试过了:
Label findbox = grouptodayerror.Controls.Find("ABC", true).FirstOrDefault() as Label;
if (findbox != null)
findbox.Text = "CDE";
但我在第一行收到错误null reference
。
我的问题是:
ControlCollection
?Tag
或仅Text
Control
?提前致谢。
答案 0 :(得分:0)
你能试试这个
吗?foreach (Label lb in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<Label>()).ToList())
{
if (lb.Tag.Equals("ABC"))
{
//Write your logic here
}
}