mechanical-legs
mechanical-legs

Reputation: 33

dynamic controls with c# being overwritten

I am attempting to add some dynamic form elements to my asp page using c# whenever a button is clicked. The code is working, but it is overwriting itself as opposed to placing the panel, label and textbox generated in one click after the elements generated in the previous click. The counter is controlled by a global variable. I am probably missing something very simple, but any help would be great. Thanks!

protected void Button1_Click(object sender, EventArgs e)
{

    Panel pnl = new Panel();
    pnl.ID = "Panel" + count.ToString();
    Panel1.Controls.Add(pnl);

    TextBox tb = new TextBox();
    tb.ID = "Textbox" + count.ToString();
    pnl.Controls.Add(tb);

    Label lbl = new Label();
    lbl.ID = "Label" + count.ToString();
    lbl.Text = "Label" + count.ToString();
    pnl.Controls.Add(lbl);
    count++;

}

You can see the effect here:

enter image description here

Upvotes: 2

Views: 808

Answers (1)

x0n
x0n

Reputation: 52430

Each time the button is clicked, you get a postback. On subsequent load of the page, asp.net has no memory of the previous controls you added in the event handler. You would need to track this yourself - in viewstate - and recreate previously added controls in the page's Init event by interrogating viewstate before the next postback is processed. If you don't recreate them in Init, they will not function correctly (e.g. they won't be able to postback themselves or otherwise contribute to the page's event lifecycle.)

Here's some more information: http://forums.asp.net/t/1186195.aspx/1

Upvotes: 1

Related Questions