Click here to Skip to main content
15,881,089 members
Articles / All Topics

Improved FindControl for Windows desktop and mobile

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Nov 2009CPOL 10.4K   2   2
An improved FindControl for Windows desktop and mobile.

A few days ago I posted some code containing an implementation for a Windows Forms version of FindControl. Aviad P. pointed out a correction and a way that the routine can be simlified. While I had intended the original code to do a breadth-first search, it was doing a combination of depth and breadth. The functionality could also be implemented with a single loop. The result of the messages, the resulting code from our communication, is shown below:

Control FindControl(string target) {
    return FindControl(this,target);
}
static Control FindControl(Control root, string target){
    if(root.Name == target)
        return root;
    List currentLevel = new List() { root };
    while (currentLevel.Count > 0)
    {
        Control match = currentLevel.FirstOrDefault(x => x.Name == target);
        if (match != null) return match;
        currentLevel = currentLevel.SelectMany(x => x.Controls.Cast()).ToList();
    }    return null;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I attended Southern Polytechnic State University and earned a Bachelors of Science in Computer Science and later returned to earn a Masters of Science in Software Engineering. I've largely developed solutions that are based on a mix of Microsoft technologies with open source technologies mixed in. I've got an interest in astronomy and you'll see that interest overflow into some of my code project articles from time to time.



Twitter:@j2inet

Instagram: j2inet


Comments and Discussions

 
GeneralYour generic argument specifications are lost in the copy/paste Pin
Aviad P.4-Dec-09 2:34
Aviad P.4-Dec-09 2:34 
GeneralRe: Your generic argument specifications are lost in the copy/paste Pin
Joel Ivory Johnson4-Dec-09 2:40
professionalJoel Ivory Johnson4-Dec-09 2:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.