Reputation: 58
I have a dynamic Label
with Tag
which is created 14 Label
and added in a GroupBox
, then, I want to search for Label
that have a Tag = "ABC"
, I have tried this :
var items = grouptodayerror.ControlCollection;
var finditem = items.Cast<Control>().FirstOrDefault(control => String.Equals(control.Tag, "ABC");
grouptodayerror
is my GroupBox
, and getting an error message
Error 1 'ControlCollection': cannot reference a type through an expression; try 'System.Windows.Forms.Control.ControlCollection' instead
I tried this too :
Label findbox = grouptodayerror.Controls.Find("ABC", true).FirstOrDefault() as Label;
if (findbox != null)
findbox.Text = "CDE";
But I'm getting error null reference
on first line.
My question is :
ControlCollection
?Tag
or just a Text
of Control
?Thanks in advance.
Upvotes: 0
Views: 3078
Reputation: 110
Can you try this one
foreach (Label lb in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<Label>()).ToList())
{
if (lb.Tag.Equals("ABC"))
{
//Write your logic here
}
}
Upvotes: 1