简体   繁体   中英

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.

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
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM