M D M D - 1 year ago 82
C# Question

Ability to find WinForm control via the Tag property

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).

Answer Source

Follow up on my comment:

private void FindTag(Control.ControlCollection controls)
    foreach (Control c in controls)
        if (c.Tag != null)

       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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download