【问题标题】:add row to table in asp在asp中向表中添加行
【发布时间】:2012-11-01 18:36:16
【问题描述】:

我想通过用户点击向表中添加行,而不是在 asp 后面的代码中这样做 然后当点击“addRowButton”时,表格中只能添加一行。所以,我在谷歌上搜索了这个问题,在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);
    }

请帮忙

【问题讨论】:

    标签: c# asp.net dynamic viewstate


    【解决方案1】:

    您需要将当前行数存储到 ViewState 字段中(使用当前 Page 上下文的 ViewState 属性)。或者将相同的信息存储在隐藏字段中,然后在页面的 OnInit 事件期间调用 AddNewRow 的次数与 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"]++
    

    【讨论】:

    • 亲爱的戴,你能解释一下你的答案吗,我的意思是你能在这里写一个代码来实现我的请求吗,我是 ASP 的初学者。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2017-04-07
    • 2016-03-01
    相关资源
    最近更新 更多