A real simple one

  • Thread starter Thread starter web1110
  • Start date Start date
W

web1110

Hi,

My documetation is deficient on this.

What is the easiest way to iteraterate over all the controls within a form
control using the foreach statement.

Thanx,
Bill
 
For fun. I made a form with a bunch of controls and tried this code in a
button on the form:

string str="";
foreach(Control tb in this.Controls) // GOOD
{
str+=str+tb.Name+"\n";
}
MessageBox.Show(str);
}

It worked but controls names are repeated several times when I expected each
one to appear only once.
 
web1110 ha scritto:
For fun. I made a form with a bunch of controls and tried this code in a
button on the form:

string str="";
foreach(Control tb in this.Controls) // GOOD
{
str+=str+tb.Name+"\n";
}
MessageBox.Show(str);
}

It worked but controls names are repeated several times when I expected each
one to appear only once.

you must use:

str+=tb.Name+"\n";

or

str=str+tb.Name+"\n";
 
Arggggggghhhhhhhhhh!!!
Thank you. One of those things where you cannot see the forest for the
trees. It was late and I guess I should have quit. Sorry for wasting
everyones time.
 
Well, maybe it was worth asking. The code you have (once corrected) will
display names of all the controls in the form's Controls collection, but it
will not necessarily get all the controls on a form. If you have a container
control (such as Panel), then any controls on the Panel will not be in the
form's Controls collection, it will be in the Panel's collection. To really
catch them all, you'd need something like this:

private void Write_Controls_to_output(Control ctrl)
{
// For debugging...
// Writes a line to output for each Control on the form

Console.WriteLine(ctrl.Name + " " + ctrl.GetType().ToString());

if ( ctrl.Controls != null && ctrl.Controls.count > 0 )
foreach( Control c in ctrl.Controls )
{
Write_Controls_to_output(c);
}
}

foreach( Control c in this.Controls)
Write_Controls_to_output(c);


-Rachel

web1110 said:
Arggggggghhhhhhhhhh!!!
Thank you. One of those things where you cannot see the forest for the
trees. It was late and I guess I should have quit. Sorry for wasting
everyones time.

web1110 ha scritto:
expected
 
Back
Top