As mentioned, dynamically added controls should be recreated on each postbacks to retain them on the page. See:
ASP.Net Persist Dynamic Controls: Dynamic Controls disappear after PostBack in ASP.Net
Here's a quick example on how to dynamically generate rows of
TextBox
controls to a
table
.
private int numOfRows = 0;
private int numOfColumns = 0;
private void GenerateTable(int colsCount, int rowsCount){
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
for (int i = 0; i < rowsCount; i++){
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++){
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
}
The code above simply creates a blank table and add it to the form. It then fill the table with columns and rows of
TextBoxes
based from the values of
rowsCount
and
colsCount
.
Now, you can call the method above on
Page_Load
event to recreate the
table
when it postbacks.
protected void Page_Load(object sender, EventArgs e){
GenerateTable(numOfColumns, numOfRows);
}
You can then call the method GenerateTable() at Button Click event like this:
protected void Button1_Click(object sender, EventArgs e){
if (int.TryParse(TextBox1.Text.Trim(), out numOfColumns) && int.TryParse(TextBox2.Text.Trim(), out numOfRows))
{
GenerateTable(numOfColumns, numOfRows);
ViewState["cols"] = numOfColumns;
ViewState["rows"] = numOfRows;
}
else
{
Response.Write("Values are not numeric!");
}
}
Just for this example, we've use two
TextBoxes
for you to be able to test the values of
numOfColumns
and
numOfRows
parameters. In your case, you could bypass it and use the value of the DropDownList selected. For example:
numOfColumns = 1;
numOfRows = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value;
GenerateTable(numOfColumns, numOfRows);
Finally, since we're done creating our
Table
with
TextBoxes
dynamically, we can grab the values entered from the dynamic
TextBox
using
Request.Form
collection. Here’s the code block below.
protected void Button2_Click(object sender, EventArgs e){
if (ViewState["cols"] != null && ViewState["rows"] != null)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
GenerateTable(int.Parse(ViewState["cols"].ToString()), int.Parse(ViewState["rows"].ToString()));
for (int i = 0; i < int.Parse(ViewState["rows"].ToString()) ; i++)
{
for (int j = 0; j < int.Parse(ViewState["cols"].ToString()); j++)
{
if (Request.Form["TextBoxRow_" + i + "Col_" + j] != string.Empty)
{
Response.Write(Request.Form["TextBoxRow_" + i + "Col_" + j] + "<BR/>");
}
}
}
}
}
}
That's it. Hope that helps.
If you are also looking for a
GridView
solution, you can check my article about:
Dynamically Adding and Deleting Rows in GridView and Saving All Rows at Once[
^]