views:

187

answers:

2

I have a web app where the user can create dynamic textboxes at run time. When the user clicks SUBMIT, the form sends data to the database and I want 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 Remove section of the code is:

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 textboxes are still visible.

Any ideas?

A: 

I would assume that your creating these controls each time the page is loaded or else when your remove code ran on postback it would fail because they would not exist.

So you need to move the create code to NOT happen with every page load by making sure it is wrapped in a if (!IsPostBacK) { ... } statement.

If you do this then you wouldn't need to remove them manually since they are created dynamically and therefore not created by default on each postback.

If you can post where the code that creates the controls is being called from, and the remove as well, I could help you a bit more.

Kelsey
I am creating one row of textboxes on page load. If the user wants to add another row, they click on "Add Another Row" button; That is in the specs. When the user submits, (lets say they created 5 additional rows), I would like to remove the 5 new rows that the user created.
user279521
Those new rows really shouldn't be there though because when it's posted back, you new page has no idea that there were 5 new rows since you dynamically created them. Maybe I am missing something... can you post how you add the new rows?
Kelsey
A: 

What I ended up doing was instead of deleting the textbox, I deleted the TableRow;

user279521