我有一個System.Web.UI.WebControls.Table帶有一個具有五個單元的ROW和五個服務器控件。我想點擊「添加新行」來創建新的行和如何在第一行單元格上設置名稱?ASP.NET - 在表中動態添加/刪除TableRow
如何做到這一點?請給我類似的教程。
這是我的代碼:
public class HelloWorldWeb : WebPart
{
protected override void CreateChildControls()
{
//table Cells Controls
TextBox txt1 = new TextBox();
txt1.Height = 19;
TextBox txt2 = new TextBox();
txt2.Height = 19;
TextBox txt3 = new TextBox();
txt3.Height = 19;
DateTimeControl dt1 = new DateTimeControl();
dt1.DateOnly = true;
DateTimeControl dt2 = new DateTimeControl();
dt2.DateOnly = true;
Button btnAdd = new Button();
btnAdd.Text = "Create New Row";
btnAdd.Click += new EventHandler(btnAdd_Click);
//Declaration one Row and Five Cells(with controls)
Table myTbl = new Table();
TableRow tRow = new TableRow();
TableCell tCellOne = new TableCell();
tCellOne.Controls.Add(txt1);
tRow.Cells.Add(tCellOne);
TableCell tCellTwo = new TableCell();
tCellTwo.Controls.Add(dt1);
tRow.Cells.Add(tCellTwo);
TableCell tCellThree = new TableCell();
tCellThree.Controls.Add(dt2);
tRow.Cells.Add(tCellThree);
TableCell tCellFour = new TableCell();
tCellFour.Controls.Add(txt2);
tRow.Cells.Add(tCellFour);
TableCell tCellFive = new TableCell();
tCellFive.Controls.Add(txt3);
tRow.Cells.Add(tCellFive);
myTbl.Rows.Add(tRow);
this.Controls.Add(new LiteralControl("<table class='ms-formbody' vAlign='top' >"));
this.Controls.Add(new LiteralControl("<tr>"));
this.Controls.Add(new LiteralControl("<td width='100' class='ms-formlabel' noWrap='nowrap' vAlign='top'>"));
this.Controls.Add(myTbl);
this.Controls.Add(btnAdd);
this.Controls.Add(new LiteralControl("</td>"));
this.Controls.Add(new LiteralControl("</tr>"));
this.Controls.Add(new LiteralControl("</table>"));
base.CreateChildControls();
}
void btnAdd_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
的結果必然是:
使靜態計數器(這是ViewState的是好的使用),並讓您的控件創建代碼循環與計數器指示的一樣頻繁。 「添加」按鈕增加計數器。 – Alexander
從我所知道的情況來看,您的按鈕點擊並沒有做任何事情。你在CreateChildControls中添加一個「EventHandler」,但這是不必要的。你只在頁面上有一個按鈕。使用「btnAdd_Click」事件並調用「CreateChildControls」函數。 –
我想你可以將行存儲在一個'List <>'中,每次點擊時在列表中添加一個新項目,然後只顯示該列表中的行。 –