0

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....

Dejan Stuparic
  • 575
  • 2
  • 13
  • 32

2 Answers2

1

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.

Community
  • 1
  • 1
bang
  • 4,982
  • 1
  • 24
  • 28
  • Yes, my control is nested. Can you give me an example. It is nested within div tag with id="page". – Dejan Stuparic Jan 25 '12 at 15:06
  • 1
    id="page" maybe isn't the best choosen id :) – bang Jan 25 '12 at 15:19
  • I call it from codebehind of page where div in question is located. I tried Page.FindControl("placeHolder") and base.FindControl("placeHolder"), with same result. And also Pages_Core core = new Pages_Core(); //page where div is Control phd = (Control)core.FindControl(ph); – Dejan Stuparic Jan 25 '12 at 15:43
  • As explained earlier: You need to call FindControl on the parent control of the control you are looking for. Not base or Page or any other object... – bang Jan 25 '12 at 15:51
  • I use master pages, so i posted mine own solution to this problem, thx anyway. – Dejan Stuparic Jan 25 '12 at 18:04
0

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.

Dejan Stuparic
  • 575
  • 2
  • 13
  • 32