简体   繁体   中英

Adding controls to a Panel in an UpdatePanel

I have a Panel in an UpdatePanel, a Button and a TextBox.

<asp:UpdatePanel ID="updatepanel1" runat="server">
<ContentTemplate>
    <asp:TextBox ID="commentBox" Rows="1" Columns="60" placeholder="Add a comment..." TextMode="MultiLine" ClientIDMode="Static" runat="server"></asp:TextBox>  
    <asp:LinkButton ID="commentButton" runat="server" OnClick="commentButton_Click"> CommentButton   </asp:LinkButton>
    <asp:Panel ID="commentPanel" runat="server"></asp:Panel>   
</ContentTemplate>
</asp:UpdatePanel>

on Button Click I am trying add what's in the TextBox to the Panel like this

Literal myComment = new Literal();
myComment.Text = "<p>"+commentBox.Text+"</p><br />";
commentPanel.Controls.Add(myComment);

This adds whats currently in the TextBox, but what was there in the panel gets removed. So every time it starts from 0 count for controls in the panel. what am I missing?

you can check this out:

List<Literal> persistControls = new List<Literal>();
protected void Page_Load(object sender, EventArgs e)
{
    // if you already have some literal populated
    if (Session["persistControls"] != null)
    {
        // pull them out of the session
        persistControls = (List<Literal>)Session["persistControls"];
        foreach (Literal ltrls in persistControls)
            commentPanel.Controls.Add(ltrls); // and push them back into the page
    }
}

protected void commentButton_Click(object sender, EventArgs e)
{
    Literal myComment = new Literal();
    myComment.Text = "<p>" + commentBox.Text + "</p><br />";
    commentPanel.Controls.Add(myComment);
    persistControls.Add(myComment);// add it to the list
    Session["persistControls"] = persistControls; // put it in the session
}
     Literal comment = new Literal();
    comment.Text="";

    Panel1.Controls.Add(comment);
    if (Panel1.Controls.Contains(comment))
    {
        comment.Text = comment.Text + "<p>" + commentbox.Text + "</p>";
    }

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