Reputation: 237
I am working in C# on an existing WinForm project. The original code uses Tag to convey hardware addressing info for a bunch of textboxes that represent certain hardware registers in a connected microcontroller system. I know how to find an unknown control by searching for its Name using the Control.ControlCollection.Find method, but it's unclear to me on whether I can find the control by the Tag (just a string in this instance).
Upvotes: 12
Views: 19739
Reputation: 4104
Follow up on my comment:
private void FindTag(Control.ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.Tag != null)
//logic
if (c.HasChildren)
FindTag(c.Controls); //Recursively check all children controls as well; ie groupboxes or tabpages
}
}
Then you can get the control name in the if statement and do whatever you want to do from there.
Just adding an Edit to this solution as it still gets the infrequent Upvote a few years later. You can also modify this solution to check the type of control that c
is and do different kinds of logic as well. So if you want to loop over all your controls and handle a Textbox
one way and a RadioButon
another way you can do that as well. I've had to do that on a few projects as well, where I was able to just slightly change the code above to make that work. Not necessarily relevant to the OP's question, but thought I'd add it.
Upvotes: 13
Reputation: 3123
public static Control FindByTag(Control root, string tag)
{
if (root == null)
{
return null;
}
if (root.Tag is string && (string)root.Tag == tag)
{
return root;
}
return (from Control control in root.Controls
select FindByTag(control, tag)).FirstOrDefault(c => c != null);
}
Pass the outermost control to it (i.e. the form or container you want to search through). Note that this includes the root control into the search.
Upvotes: 7
Reputation: 30688
You can use LINQ
to find controls based on Tag
var items = parentControl.ControlCollection;
var item = items.Cast<Control>().FirstOrDefault(control => String.Equals(control.Tag, tagName));
Upvotes: 12