uh ... i hope you are not a novice to asp.net. because otherwise it may end up in a horror!
reasons:
if you dynamically create controls, they should be present, after the first postBack, each postBack before AttachPostData SecondTry
. you have to give the controls the same ids after postBack again - otherwise viewState/postBackData won't get attached and it will end up in an exception.
so assume you all know this, here's some basic sceleton:
<asp:PlaceHolder runat="server" ID="phDynamicControls" />
and codeBehind
function /* add name and correct signature here - eventHandler for saveButton click-event */
{
// TODO rebuild controls from other postBacks somewhere
var control = new TextBox
{
ID = "myUniqueID"
}
this.phDynamicControls.Controls.Add(control);
}
extending it, to avoid pitfalls, do the following for your page!
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
// this will only be executed if postback
// recreate controls from former postback
}
protected override object SaveViewState()
{
// TODO persist control hirarchie in here!! to allow restoring on next LoadViewState()
return base.SaveViewState();
}
a very easy approach would be:
why not use a repeater
<asp:Repeater runat="sever" ID="repDynamicControls">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtCustom"/>
</ItemTemplate>
</asp:Repeater>
your codebehind
function /* add name and correct signature here - eventHandler for saveButton click-event */
{
// TODO find out number of items!
var items = 3;
this.repDynamicControls.DataSource = Enumerable.Range(0, items); // zero-offset here
this.repDynamicControls.DataBind();
}
but you still got following problem: preserve repeater data (binding) also if no event of your generate new item
-button is fired.
in the end you will end up with binding at least 2 times:
- 1st on LoadViewState
- 2nd (optional) on eventHandler