Amieru Rain
Amieru Rain

Reputation: 58

Find control by tag on WinForm

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 :

  1. How can I get the ControlCollection?
  2. Did the second code can find a Tag or just a Text of Control?
  3. Is there any way to accomplish this?

Thanks in advance.

Upvotes: 0

Views: 3078

Answers (1)

Jitendra.Suthar
Jitendra.Suthar

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

Related Questions