tags:

views:

487

answers:

3

I have a Panel with a collection of controls in it. How can I get the index of a specific control when iterating through them? I'm using foreach to iterate, but there's no Index property. Should I use for x = 0... and return x when my match is made, or what?

+4  A: 

You could use:

panel.Controls.IndexOf(control);

Or you could iterate over them with a for loop instead of a foreach loop. Or you could just create an index that you increment inside of the foreach loop.

Steven Behnke
+1  A: 

You can just use the IndexOf method. Something like panel1.Controls.IndexOf(textBox1);

BFree
A: 

To answer the specific question you asked, yes, I'd use

for(x = 0; x < panel.Controls.Count; i++)

However, if you are dynamically ading controls to the panel, you might consider giving them unique names or other identifing attributes via the .Name or .Tag properties.

Then you can discriminate among your child controls with more precision.

Hope this helps...

AlfredBr