How do I add textboxes to an existing table of textboxes? How do I retrieve the values of the newly added textboxes? The challenge here is that dynamically added controls are not automatically recreated for you by the ASP.Net framework on page postback. This means if you create textboxes dynamically, then you have to re-create these textboxes on every postback. In the ASPX page, create asp:Table and asp:HiddenField as below:
<asp:HiddenField ID="hdnCount" Value="1" runat="server" />
<asp:Table ID="tblMain" runat="server">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Name</asp:TableHeaderCell>
<asp:TableHeaderCell>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click"/>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtName1" runat="server" Width="200"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
In the code-behind, the textboxes can be created using code like this in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
CreateTextBoxes();
}
private void CreateTextBoxes()
{
int count = int.Parse(hdnCount.Value);
// Recreate the textboxes on each postback
for (int i = 2; i <= count; i++)
{
TextBox tb = new TextBox();
tb.ID = "txtName" + i.ToString();
tb.Width = 200;
tb.Text = Request.Form["txtName" + i.ToString()];
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
tblMain.Rows.Add(tr);
}
}
The code for adding and saving textbox values is as follows:
protected void btnAdd_Click(object sender, EventArgs e)
{
int count = int.Parse(hdnCount.Value);
count++;
hdnCount.Value = count.ToString();
TextBox tb = new TextBox();
tb.ID = "txtName" + count.ToString();
tb.Width = 200;
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
tblMain.Rows.Add(tr);
}
protected void btnSave_Click(object sender, EventArgs e)
{
int rowCount = int.Parse(hdnCount.Value);
for (int rowNumber=1; rowNumber<=rowCount; rowNumber++ )
{
TextBox tb = (TextBox)tblMain.Rows[rowNumber].Cells[0].FindControl
("txtName" + rowNumber.ToString());
if (tb != null)
Response.Write(tb.Text + "<br/>");
}
}
|