Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...