如何通过按下按钮动态地向表中添加行?

时间:2013-09-15 08:58:59

标签: asp.net

我想通过单击按钮向表控件添加行。我尝试使用下面的代码,但收到错误,有人可以帮忙吗?

protected void btn_Click(object sender, EventArgs e)
{
    //Table table = (Table)Page.FindControl("tblName");
    TableRow tr = new TableRow();
    tr.Cells.Add(new TableCell());
    tr.Cells.Add(new TableCell());
    tr.Cells.Add(new TableCell());
    tr.Cells[0].Text = TextBox1.Text;
    tr.Cells[1].Text = TextBox2.Text;
    tr.Cells[2].Text = TextBox3.Text;
    //add the row to the existing table.
    this.tblName.Rows.Add(tr);
    //this.tblName.Rows.Add();
}

-------------------- asp.net ------------------------ -

  <form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="btn_Click" />
    <table id="tblName" Runat="server" style="width:100%;">
        <tr>
            <td>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
            <td>
               <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
            <td>
               <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
        </tr>

    </table>
    <br />
</div>
</form>

1 个答案:

答案 0 :(得分:1)

您非常接近,而不是System.Web.UI.WebControls.TableRow您应该使用System.Web.UI.HtmlControls.HtmlTableRow,因为您的表格类型为System.Web.UI.HtmlControls.HtmlTable

无论如何,你现有的代码缺少一些逻辑,因为它总是只添加一行,覆盖了你预先添加的内容。要继续添加,您必须存储已在某处添加的内容,理想的位置是ViewState集合。

优化的代码是:

//build array of new values
string[] currentValues = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };

//get list from view state and append new values
List<string[]> tableRowValues = (List<string[]>)ViewState["AppendedRows"];
if (tableRowValues == null)
    tableRowValues = new List<string[]>();
tableRowValues.Add(currentValues);

//add rows to table
tableRowValues.ForEach(values =>
{
    System.Web.UI.HtmlControls.HtmlTableRow tr = new System.Web.UI.HtmlControls.HtmlTableRow();
    foreach (string value in values)
    {
        System.Web.UI.HtmlControls.HtmlTableCell cell = new System.Web.UI.HtmlControls.HtmlTableCell();
        cell.InnerHtml = value;
        tr.Cells.Add(cell);
    }
    this.tblName.Rows.Add(tr);
});

//update global container
ViewState["AppendedRows"] = tableRowValues;