views:

342

answers:

4

I put a link on a page and onclick i wrote some code to add some controls after clicking,

    DropDownList newDropdownlist = new DropDownList();
    panel.Controls.Add(newDropdownlist);
    CheckBox newChkbox = new CheckBox();
    panel.Controls.Add(newChkbox);
    TextBox txt = new TextBox();
    txt.ID = "txtPhoneValue";
    panel.Controls.Add(txt);

My Problem is when i click on this link it add these controls one time, but if i clicked again it don't add more, seams its removing the previous added controls and re add them again.

I want to add more and more each link click.

+4  A: 

Ok, these added controls are not persisted anywhere between postbacks. So, you should add them every time the page reloads.

Consider using some flags (stored in the Session for example) to indicate that additional controls must be added.

amartynov
A: 

How is this link construct??

If your link control is an html control (client control) the behaviour you're experienced is right.

jaloplo
+2  A: 

Your controls're disappearing, as they're not stored anywhere (the page forgets about them on postback). Remember that, on each postback, your page has to be recreated.

There're quite a few good articles about working with dynamically created controls. Also to fully understand what the problem is, it's neccessary to familiarize yourself with the page lifecycle.

Here're two articles that really helped me:

snomag
+2  A: 

You need to re-create the controls (with the same IDs!) on post-back, you can do this in the CreateChildControls method.

It's worth looking at the Page Life-Cycle of ASP.NET to understand when and where stuff can be modified. If it's to late, it won't get added to the ViewState etc, so it's worth understanding especially when using dynamically created controls.

Kieron