Improved FindControl for Windows desktop and mobile





0/5 (0 vote)
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; }