如何在asp.net表中动态添加行?

如何从服务器端添加表中的行?

if (!Page.IsPostBack) { Session["table"] = TableId; } else { TableId = (Table)Session["table"]; } protected void btnAddinRow_Click(object sender, EventArgs e) { num_row = (TableId.Rows).Count; TableRow r = new TableRow(); TableCell c1 = new TableCell(); TableCell c2 = new TableCell(); TextBox t = new TextBox(); t.ID = "textID" + num_row; t.EnableViewState = true; r.ID = "newRow" + num_row; c1.ID = "newC1" + num_row; c2.ID = "newC2" + num_row; c1.Text = "New Cell - " + num_row; c2.Controls.Add(t); r.Cells.Add(c1); r.Cells.Add(c2); TableId.Rows.Add(r); Session["table"] = TableId; } 

在调试中我发现了“TableID”中的数字,但没有绘制行。

你对这个问题有所了解吗? 谢谢

我认为你对动态控件感到困惑…如果你动态地创建表中的每一行…你需要在每个页面周期创建它(具有相同的名称)..是否回发。 ..

简单来说,如果你创建的东西不在.aspx(Tag)页面中,那么在你的代码中…在每次回发中都做…

在您的代码中,您正在从会话中检索表,但您没有将其再次添加到表单中……以下行就是这样做的。

  this.form1.Controls.Add(TableId); 

这是一个工作代码,针对您的问题…希望这会有所帮助。 让我知道,如果您有任何问题…您也可以尝试使用对象Datasource的DataGrid …这将帮助您保留回发数据,而无需将其写入数据库。

  Table TableId = new Table(); protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { TableId.ID = "MyTable"; } else { TableId = (Table)Session["table"]; this.form1.Controls.Add(TableId); } } protected void Page_PreRender(object sender, EventArgs e) { Session["table"] = TableId; } protected void btnAddinRow_Click(object sender, EventArgs e) { int num_row = (TableId.Rows).Count; TableRow r = new TableRow(); TableCell c1 = new TableCell(); TableCell c2 = new TableCell(); TextBox t = new TextBox(); t.ID = "textID" + num_row; t.EnableViewState = true; r.ID = "newRow" + num_row; c1.ID = "newC1" + num_row; c2.ID = "newC2" + num_row; c1.Text = "New Cell - " + num_row; c2.Controls.Add(t); r.Cells.Add(c1); r.Cells.Add(c2); TableId.Rows.Add(r); Session["table"] = TableId; } 

我想知道为什么你会使用一个表,而不是具有如此强大的GridView控件,你可以很容易地完成这个?

GridView可以与DataTable连接,因为它是自己的DataSource ,因此,如果您需要创建一个新行,您需要做的就是在DataTable创建一个新的DataRow并再次绑定它。

您可以使用javascript(Ajax调用)或代码隐藏来使用它。

 DataTable dt = (DataTable)Session["myData"]; DataRow dr = dt.NewRow(); dt.Rows.Add(dt); myGridView.DataSource = dt; myGridView.DataBind(); 

你不需要担心ID,因为它们将是独一无二的,例如,在保存时,你可以轻松遍历所有行并按行执行所需的操作,例如

 public void SaveData() { myBusinessObjectCollection = new myBusinessObjectCollection(); foreach (GridViewRow row in myGridView.Rows) { myBusinessObjectCollection.Add( new myBusinessObject { C1 = ((TextBox)row.FindControl("txtNewC1")).Text, C2 = ((TextBox)row.FindControl("txtNewC2")).Text }); } myBusinessObjectCollection.Save(); } 

在ASP.NET中,每次回发都会重新创建控件,因此在会话中保存表上的链接没有意义。

在会话(或视图状态)中存储一些描述您的表的结构(DataTable或强类型对象的集合),在单击按钮事件上添加此结构中的行,并在OnPreRender事件上使用此结构重新绑定表。