When dynamically creating controls you need to make sure that you are reloading the controls during any postback event. The controls need to be loaded with the same ID and in the same order as they were created. What @adriancs posted should work as long as the user has only clicked once on the button that adds the textboxes. What I generally do in a situation like this is save the count of the dynamically added controls using a session variable, then during a postback I can reload the controls using the count from the session variable.
public int TextBoxCount
{
get
{
object temp = Session["TextBoxCount"];
return temp == null ? 0 : (int)temp;
}
set
{
Session["TextBoxCount"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
AddTextBox();
}
void AddTextBox()
{
Table tblTxtBox = new Table();
for (int i = 0; i < TextBoxCount; i++)
{
TableCell tblcell = new TableCell();
TableRow tblrow = new TableRow();
TextBox txtBox = new TextBox();
txtBox.ID = "txtBox" + i;
tblcell.Controls.Add(txtBox);
tblrow.Cells.Add(tblcell);
tblTxtBox.Rows.Add(tblrow);
}
Panel1.Controls.Add(tblTxtBox);
}
protected void btnItem_Click(object sender, EventArgs e)
{
Table tblTxtBox = new Table();
int start = TextBoxCount;
TextBoxCount += 5;
for (int i = start; i < TextBoxCount; i++)
{
TableCell tblcell = new TableCell();
TableRow tblrow = new TableRow();
TextBox txtBox = new TextBox();
txtBox.ID = "txtBox" + i;
tblcell.Controls.Add(txtBox);
tblrow.Cells.Add(tblcell);
tblTxtBox.Rows.Add(tblrow);
}
Panel1.Controls.Add(tblTxtBox);
}
That may need a little tweaking as I'm just working from memory right now, but hopefully it helps some