0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.