繁体   English   中英

使用面板RenderControl方法时无法找到具有ID的控件

[英]Unable to find control with id when using the panel RenderControl Method

我正在尝试在asp.net中动态创建一个表单,并通过在呈现的控件上执行文本替换来在页面上呈现它。

(我不能只是将控件推到页面上的面板上,那是理想的情况,我现在不会遇到这个问题)

我创建一个标签,文本框和一个按钮,并将它们全部添加到面板中。 然后使用TextWriter将该面板呈现为字符串,然后使用它在副本上执行替换。

    Label lbl = new Label();
    lbl.Text = "Enter Amount";
    lbl.Attributes.Add("style", "width:25%; vertical-align:middle;");
    lbl.CssClass = "donate-label";
    lbl.ID = "lblAmount";

    TextBox tb = new TextBox();
    tb.ID = "tbAmount";
    tb.Attributes.Add("style", "padding-left:25px; width:50%;");

    lbl.AssociatedControlID = tb.ID;

    Button b = new Button();
    b.ID = "btnDonate";
    b.Text = "Make a Donation";
    b.CssClass="block-btn right-arrow red-bg right";
    b.Click += new EventHandler(btnDonate_Click);
    b.Attributes.Add("style", "display:table-cell; margin-top:0; width:40% !important;");

    Panel pnlForm = new Panel();
    pnlForm.CssClass="form clearfix donate-form";
    pnlForm.Attributes.Add("style", "width:70%");

    pnlForm.Controls.Add(lbl);
    pnlForm.Controls.Add(tb);
    pnlForm.Controls.Add(b);

现在,如果我要将上述面板添加到页面上已经存在的面板中,它将可以正常工作并按预期工作,但是控件呈现会导致它在某处中断。

    TextWriter myTextWriter = new StringWriter();
    HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);

    pnlForm.RenderControl(myWriter);

    string body = p.Copy.Replace("##donate##", myTextWriter.ToString());

我得到的错误如下:

找不到ID为'tbAmount'且与标签'lblAmount'相关联的控件。

第146行:pnlForm.RenderControl(myWriter);

如果我删除了标签的assoicatedControlID,它可以正常工作,但是不幸的是,它使我的标签呈现为不是我需要的范围,我需要将其呈现为带有“ for”属性的标签。

最简单的方法是在其中使用带有html标记的文字

    Literal lbl = new Literal();
    lbl.Text = "<Label For='tbAmount' style='width:25%; vertical-align:middle;' class='donate-label' > Enter Amount </label>";
    lbl.ID = "lblAmount";

顺便说一句,使tbAmount id为静态,这样您就不会为文本框得到任何无法预测的id

    tb.ClientIDMode= System.Web.UI.ClientIDMode.Static

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM