0
protected void lbChatFriend_Click(object sender, EventArgs e)
        {
            ChatDivContent.Visible = true;
            System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
            createDiv.ID = "div";
            createDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Yellow");
            createDiv.Style.Add(HtmlTextWriterStyle.Position, "relative");
            createDiv.Style.Add(HtmlTextWriterStyle.Color, "Red");
            createDiv.Style.Add(HtmlTextWriterStyle.Height, "50px");
            createDiv.Style.Add(HtmlTextWriterStyle.Width, "50px");
            createDiv.InnerHtml = " I'm a div ";
            string chatFriend = ((LinkButton)sender).Text;
            createDiv.Attributes["title"] = chatFriend;
            ChatDivContent.Controls.Add(createDiv);
        }
 <div id="ChatDivContent">
     <DIV id="div" style="background-color:Yellow;position:relative;color:Red;height:50px;width:50px;"
 title="dinesh"> I'm a div </DIV></div>

<----这是我每次回发的输出

我做错了吗?

4

1 回答 1

0

I assume that you're not recreating the old controls on postback(f.e. when the user clicks on that LinkButton). Therefor only the recently created div is displayed.

You have to recreate all dynamically created controls on every postback(in load event at the latest). You also have to ensure that they get the same ID as before to trigger events and maintain ViewState.

If you know the number of controls to create(which could be stored in ViewState) you can derive the ID from the counter variable by appending it to the control-id. Then you can recreate them with the correct ID in page's init event.

Recommandable readings:

Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their DataSource and call DataBind().

Here is an answer of me on a similar question with implementation.

于 2012-07-22T11:27:37.320 回答