Reputation: 2385
I have a task to generate a XML file of the layout, but I seem to have a problem recognizing Panel controls on the form. To recognize the objects, I use something like this:
foreach (Control c in this.Controls) {
if (c is Button) {
//generate XML...
} else if (c is Panel) {
//generate XML...
}
}
It finds all the controls just fine, but not the Panel objects. Can anyone tell me what am I doing wrong here? Is panel not a Control?
Upvotes: 1
Views: 3192
Reputation: 27633
A panel is a Control, but you only get the Controls which are directly in the Form, not the ones that are inside other Controls.
So how about something like this:
void DoRecursive(Control ctrl)
{
foreach (Control subCtrl in ctrl.Controls) DoRecursive(subCtrl);
if (ctrl is Button) etc.
}
Or perhaps your //generate XML...
as a Button exits the foreach
. Perhaps it has a break
.
Upvotes: 1
Reputation: 116108
You can use this recursive function .
var panels = FindControls<Panel>(aForm).ToList();
IEnumerable<T> FindControls<T>(Control ctrl) where T: Control
{
foreach (Control c in ctrl.Controls)
{
if (c.GetType() == typeof(T)) yield return (T)c;
foreach (var subC in FindControls<T>(c))
yield return subC;
}
}
Upvotes: 1
Reputation: 8337
Your code should work. Try modifying the code to not do an else if
and see if you can locate the Panel:
foreach (Control c in this.Controls) {
if (c is Panel) {
MessageBox.Show("Hey, I found the " + c.Name + " panel!");
}
}
We could also try locating it by name and seeing what type of a control it is:
foreach (Control c in this.Controls) {
// Looks for a control called 'panel1' - put in your panel's name
if (c.Name == "panel1") {
MessageBox.Show("Hey, I found a " + c.GetType().ToString());
}
}
Upvotes: -1
Reputation: 305
I tried your code with a simple form having one button and one panel on the form and one button inside the panel. It worked for me finding the first button and the panel. Maybe the problem is you want to access the controls whose parent is the panel?
Upvotes: 0