在UpdatePanel中向Panel添加控件

时间:2013-04-15 02:54:47

标签: c# asp.net updatepanel

我在UpdatePanel,Button和TextBox中有一个Panel。

<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点击我正在尝试将TextBox中的内容添加到Panel中,如下所示

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

这会在TextBox中添加最新内容,但是面板中的内容会被删除。 因此,每次从面板中的控件的0计数开始。我错过了什么?

2 个答案:

答案 0 :(得分:1)

你可以看看:

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
}

答案 1 :(得分:1)

     Literal comment = new Literal();
    comment.Text="";

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