簡體   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