我想通过用户单击将行添加到表中,而不是在 asp 的代码后面执行此操作时然后当单击"添加行按钮"时,只能将一行添加到表中。所以,我在谷歌上搜索这个问题,在asp中看到一些关于"ViewState"的文章,导致这个问题,但无法理解我如何使用或更改"ViewState"来解决这个问题。
这是我在ASP页面中的表的模板:
<table runat="server" ID="myTable">
<tr><td>
<asp:textbox runat="server" ID="txt1"></asp:textbox>
</td></tr>
</table>
我正在使用此代码将一些带有特定单元格的行添加到表中:
protected void AddNewRow(object sender, EventArgs e)
{
HtmlTable tbl = (System.Web.UI.HtmlControls.HtmlTable)this.FindControl("myTable");
HtmlTableCell cell = new HtmlTableCell();
HtmlTableRow row = new HtmlTableRow();
TextBox txt = new TextBox();
txt.ID = "txtTest";
cell.Controls.Add(txt);
row.Controls.Add(cell);
int rowNumber = tbl.Rows.Count;
tbl.Controls.AddAt(rowNumber, row);
}
请帮忙
您需要将当前行数存储到 ViewState 字段中(使用当前页面上下文的 ViewState
属性)。或者将相同的信息存储在隐藏字段中,然后在页面的OnInit
事件期间调用 AddNewRow
ViewState 的次数与 ViewState 所说的次数相同。
这里有一些伪代码:
During OnInit:
Is this a postback? If so...
Read the number of table-rows N from ViewState["RowCount"]
For(I=0 to N) AddTableRow()
During AddRow_ClickHandler
AddTableRow()
ViewState["RowCount"]++