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?