从后面的代码中按名称获取div控件

时间:2012-01-25 14:43:25

标签: c# controls ascx findcontrol

好的,我想通过id来访问div控制,这是从C#代码动态改变的。也许代码会更清楚:

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();
        }

和ascx部分是:

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

它通过编译时间,但phd处于空值,而不是控制值。如果我像这样直接访问控件,它工作正常:

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

提前谢谢....

2 个答案:

答案 0 :(得分:1)

FindControl仅查找第一级中的控件,因此如果您的控件位于控件树中,则需要编写自己的嵌套FindControl以使其工作。

请查看ASP.NET Is there a better way to find controls that are within other controls?以获取更多信息。

或者如果您有父(页面),它应该可以直接在该控件上调用page.FindControl(&#34; placeHolder1&#34;)。

答案 1 :(得分:0)

由于@bang,我认为嵌套存在问题。但由于我使用母版页来显示我的内容,这是最适合我的解决方案:

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();

        }

谢谢@bang,你把我推向正确的方向。