foreach ImageButton problem

V

Varangian

Hello

how come foreach(ImageButton imgbtn in Page.Controls) doesn't work ?

whats wrong in that statement? what should I do? I need to go through
each ImageButton in the Page, without going through all the other
controls.
thanks
 
T

Teemu Keiski

That loop goes through all controls on first-level on Page's Controls
collection and tries to cast each and every of them into ImageButton, which
obviously won't work. And it's not recursive so it doesn't actually go
through all the controls.

Example which goes through all controls, and does something for every
TextBox

[C#]
private void LoopTextBoxes (Control parent)
{
foreach (Control c in parent.Controls)
{
TextBox tb = c as TextBox;
if (tb != null)
//Do something with the TextBox

if (c.HasControls())
LoopTextBoxes(c);
}
}

And start it by

LoopTextBoxes(Page);
 
V

Varangian

I'm doing

foreach (Control ctrl in Page.Controls)
{
if (ctrl is ImageButton)

..... it doesn't work though, i.e. its not finding the ImageButton..
even though the ImageButtons are in the Page. They are in an "absolute"
position.

what should I do ?
 
T

Teemu Keiski

Controls being absolutely positioned does not have impact on this. As I
said, you need to do it in recursive manner. Page.Controls representys only
the top-level controls on the Page and most probably contains only three
controls (2 literal controls and HtmlForm between them). Your ImageButtons
would be child controls of HtmlForm (since they are contained inside < form
runat="server">), and therefore iterating just Page.Controls won't get them.

Pick up my previous code as is, just change TextBox to ImageButton and use
it. It doesn't loop just Page.Controls but goes through all controls on the
page as it first goes through Page's Controls, checks if each and every
control has child controls and if they have, goes through them too (as long
as there are controls, no matter hpw deep the hierarchy)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top