count controls on a page

A

androidsun

I have many image button controls on a page. I am trying to find an
easy way to loop through each of the image buttons and add client sided
script to its Attributes collection. I am thinking to use

foreach(ImageButton btnThis in this)
btnThis.Attributes("onclick","bla bla bla");

but it does not work. Your recommendation is appreciated.
 
S

Scott M.

How about this:

Dim myControl As Object

For Each myControl In Page.Controls
If myControl.GetType() Is ImageButton.GetType() Then
CType(myControl, ImageButton).Attributes.Add("onClick", "bla bla"))
End If
Next
 
A

androidsun

Thanks for the help. I tried the suggested code, but all I could get
was the System.Web.UI.LiteralControl outside of the Form tag and the
System.Web.UI.HtmlControls.HtmlForm itself. Nothing inside the form
was iterated. The following is my test code.

int i=0;
string trIds="";
foreach (Control c in this.Controls)
{
if (c is System.Web.UI.WebControls.ImageButton)
{
i++;
}
strIds += "<p>" + c.ID + ":" + c.GetType().ToString() + "</p>";
}

lblTest.ext = i>0 ? i.ToString() : strIds;
 
A

androidsun

With further research, I found that the code would only iterate the
immediate child element but not child element contained within the
immediate child. I just add another iteration to the mix:
string strIds="";
foreach (Control c in Page.Controls)
{
if (c is System.Web.UI.HtmlControls.HtmlForm)
{
foreach (Control cc in c.Controls)
{
if (cc is System.Web.UI.WebControls.ImageButton)
{
i++;
strIds += "<p>" + cc.ID + ":" + cc.GetType().ToString() + "</p>";
}
}
}
}

lblError.Text = strIds;
 
S

Steve C. Orr [MVP, MCSD]

You should make the function recursive like I showed in my example, that way
it will work no matter how deeply your controls are nested.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top