Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...