简体   繁体   中英

Adding a row to an ASP.NET table overwrites previous rows

I have a table for data entry that has an AJAX ComboBox and an HTML text input in each row. I haven't been able to dynamically add rows with ComboBoxes through Javascript, so I made an "Add Row" button. While adding rows initially to populate the data works, the button-fired event deletes those rows and so the table only has the new row. Both of these methods use Table.Rows.Add(row), and the rows are generated through the same method for the initial and button-fired row additions.

Here is my code to generate the row:

protected System.Web.UI.HtmlControls.HtmlTableRow getEmptyRow(int rowNum, bool script)
{
    HtmlTableRow row = new HtmlTableRow();
    HtmlTableCell a = new HtmlTableCell();
    a.Style.Add("width", "75%");
    var chgsarray = d.WaterRates.Select(q => q.Name)
        .Where(q => !q.Contains("test"))
        .OrderBy(q => q); 

    AjaxControlToolkit.ComboBox t = new AjaxControlToolkit.ComboBox() { ID = "chrgName" + rowNum, AutoPostBack = false, DataSource = chgsarray, AutoCompleteMode = AjaxControlToolkit.ComboBoxAutoCompleteMode.SuggestAppend, ItemInsertLocation = AjaxControlToolkit.ComboBoxItemInsertLocation.Append, DropDownStyle = AjaxControlToolkit.ComboBoxStyle.DropDown };
    t.DataBind();
    t.Text = "";

    a.Controls.Add(t);
    row.Cells.Add(a);
    a = new HtmlTableCell();
    a.Style.Add("width", "25%");
    a.InnerText = "$";
    HtmlInputText tc = new HtmlInputText() { ID = "chrgChrg" + rowNum, Name = "chrgChrg" + rowNum, ViewStateMode = ViewStateMode.Disabled, ClientIDMode = ClientIDMode.Static };
    tc.Style.Add("width", "182px");

    a.Controls.Add(tc);
    row.Cells.Add(a);
    return row;
}

And the code adding the row upon button press is simple enough:

protected void Add_Row(Object sender, EventArgs e)
{
    int k = -1;
    for (int i = 0; Request.Form.AllKeys.Contains("ctl00$MainContent$chrgChrg" + i); i++)
        k++;
        ChargesTable.Rows.Add(getEmptyRow(k+1, true));
}

So how can I preserve the existing rows when adding a new row?

Remember that the web is stateless.

Unless told otherwise.

You are doing nothing to preserve your table rows across postbacks. The original <asp:Table> will be restored on each postback.

You would have to keep a list of the data for the rows in Session state, then on each postback, recreate all the rows, then add the row on your button click.

Even better, use a GridView and bind it to the data in session state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM