IntroductionA 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. CodeSnippetControl 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;
}Happy coding. |