Dejan Stuparic
Dejan Stuparic

Reputation: 595

Get div control by name from codebehind

Ok, I want to access div control by id witch is changed dynamically from C# code. Maybe it will be clearer with code:

string divHtml = "";
        for (int j = 1; j < 4; j++)
        {
            string ph = "placeHolder" + j;

            Control phd = (Control)FindControl(ph);
            StringWriter sw = new StringWriter();
            HtmlTextWriter w = new HtmlTextWriter(sw);
            phd.RenderControl(w);
            divHtml = divHtml + sw.GetStringBuilder().ToString();
        }

and ascx part is:

<div runat="server" id="placeHolder1" class="placeholder" >                
</div>

It pass compile time but phd is at null value, not to the value of control. It works fine if i access control directly like this:

StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
placeHolder1.RenderControl(w);
divHtml = divHtml + sw.GetStringBuilder().ToString();

Thank you in advance....

Upvotes: 0

Views: 10617

Answers (2)

bang
bang

Reputation: 5221

FindControl finds only controls in the first level, so if your control is located down in the control tree you need to write your own nested FindControl to make it work.

Have look at ASP.NET Is there a better way to find controls that are within other controls? for more info.

Or if you have the parent (page) it should work to call page.FindControl("placeHolder1") on that control directly.

Upvotes: 1

Dejan Stuparic
Dejan Stuparic

Reputation: 595

I figured that it is problem with nesting, thanks to @bang. But since I use master page to display my content, this is solution that is best for me:

for (int j = 1; j < 4; j++)
        {
            string ph = "placeHolder" + j;

            ContentPlaceHolder cph = this.Master.FindControl("MainContent") as ContentPlaceHolder;
            Control ctrlPh = cph.FindControl(ph);

            StringWriter sw = new StringWriter();
            HtmlTextWriter w = new HtmlTextWriter(sw);
            ctrlPh.RenderControl(w);
            divHtml = divHtml + sw.GetStringBuilder().ToString();

        }

Thank you @bang, you pushed me in right direction.

Upvotes: 0

Related Questions