HardCode
HardCode

Reputation: 2025

how to loop through asp.net control dynamically?

I created 4 place holder in aspx page. I named them placeHolder1, placeHolder2, placeHolder3, placeHolder4. How do I add content to these place holder dynamically in the loop? I know I could replicate four different times, but I want to save some code and do it in the loop. Is it actually possible to do so?

Upvotes: 0

Views: 1633

Answers (2)

jbkkd
jbkkd

Reputation: 1550

Something like this should work:

for (int i = 1; i <= 4; i++)
{
 PlaceHolder myControl = FindControl("placeHolder" + i) as PlaceHolder;
 //Do whatever with control;
}

Upvotes: 1

Paul Aldred-Bann
Paul Aldred-Bann

Reputation: 6020

You can loop through all controls on the page, and find the Type you're interested in like this:

foreach (Control ctrl in this.Controls)
{
    if (ctrl is ContentPlaceHolder)
    {
        ContentPlaceHolder cph = (ContentPlaceHolder)ctrl;

        if (cph.ID == "placeHolder1")
        {
            // do whatever
        }
    }
}

I haven't tested this code, but it serves to give the general idea of how you'd iterate through your place holders.

Upvotes: 3

Related Questions