[英]How can I dynamically add rows to a table by pressing a button?
我想通過單擊按鈕將行添加到表控件中。 我嘗試使用下面的代碼,但出現錯誤,有人可以幫忙嗎?
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>
你是非常接近的,而不是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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.