简体   繁体   中英

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

I am trying to dynamically create a form in asp.net and render it out on the page by performing a text replace on the rendered controls.

(I cannot just push the controls to a panel on the page, that would be the ideal situation and I wouldn't be having this problem right now)

I create a label, textbox and a button and add them all to a panel. This panel is then rendered into a string using a TextWriter, which I then to use perform my replace on my copy.

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

Now if I was to add the above panel to a panel that already existed on the page, it would work perfectly and as expected, but the control rendering is causing it to break somewhere..

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

    pnlForm.RenderControl(myWriter);

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

The error I get is as follows:

Unable to find control with id 'tbAmount' that is associated with the Label 'lblAmount'.

Line 146: pnlForm.RenderControl(myWriter);

If I removed the assoicatedControlID for my label it works fine, but unfortunately it renders my label as a span which isn't what I need, I need it rendered as a label with a 'for' attribute.

The easiest way is to use literal with html tags inside it

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

by the way make the tbAmount id static so you dont get any unpredictable id for your textbox

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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