2

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

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>
4

1 回答 1

1

你非常接近,而不是System.Web.UI.WebControls.TableRow你应该使用System.Web.UI.HtmlControls.HtmlTableRow,因为你的表是 type 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;
于 2013-09-15T09:20:22.507 回答