Controls.remove () method not working in asp.net
I have a web application where a user can create dynamic text boxes at runtime. When the user clicks on the SUBMIT button, the form is submitting data to the database and I want to remove the dynamic controls.
The controls are created in the following code:
Table tb = new Table();
tb.ID = "tbl";
for (i = 0; i < myCount; i += 1)
{
TableRow tr = new TableRow();
TextBox txtEmplName = new TextBox();
TextBox txtEmplEmail = new TextBox();
TextBox txtEmplPhone = new TextBox();
TextBox txtEmplPosition = new TextBox();
TextBox txtEmplOfficeID = new TextBox();
txtEmplName.ID = "txtEmplName" + i.ToString();
txtEmplEmail.ID = "txtEmplEmail" + i.ToString();
txtEmplPhone.ID = "txtEmplPhone" + i.ToString();
txtEmplPosition.ID = "txtEmplPosition" + i.ToString();
txtEmplOfficeID.ID = "txtEmplOfficeID" + i.ToString();
tr.Cells.Add(tc);
tb.Rows.Add(tr);
}
Panel1.Controls.Add(tb);
The "Delete" section of the code:
Table t = (Table)Page.FindControl("Panel1").FindControl("tbl");
foreach (TableRow tr in t.Rows)
{
for (i = 1; i < myCount; i += 1)
{
string txtEmplName = "txtEmplName" + i;
tr.Controls.Remove(t.FindControl(txtEmplName));
string txtEmplEmail = "txtEmplEmail" + i;
tr.Controls.Remove(t.FindControl(txtEmplEmail));
string txtEmplPhone = "txtEmplPhone" + i;
tr.Controls.Remove(t.FindControl(txtEmplPhone));
string txtEmplPosition = "txtEmplPosition" + i;
tr.Controls.Remove(t.FindControl(txtEmplPosition));
string txtEmplOfficeID = "txtEmplOfficeID" + i;
tr.Controls.Remove(t.FindControl(txtEmplOfficeID));
}
}
However, the text boxes are still visible.
Any ideas?
a source to share
I would suggest that you create these controls every time the page is loaded, and when you remove the code on the callback it will fail because they will not exist.
So you need to move your create code to NOT happen with every page load, making sure it's wrapped in a statement if (!IsPostBacK) { ... }
.
If you do this, you will not need to delete them manually, as they are dynamically generated and therefore not created by default for every postback.
If you can post where the code from which the controls are being created is called from and also remove, I could help you a little more.
a source to share