【发布时间】:2016-08-14 20:28:09
【问题描述】:
我有一个 System.Web.UI.WebControls.Table,其中一行包含五个单元格和五个服务器控件。我想在单击“添加新行”时创建一个新行和如何在第一行单元格上设置名称?
如何做到这一点?请给我类似的教程。
这是我的代码:
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 可以使用的地方),并让您的控件创建代码循环按照该计数器指示的频率进行。 “添加”按钮会增加计数器。
-
据我所知,您的按钮单击没有任何作用。您在 CreateChildControls 中添加了一个“EventHandler”,但这是不必要的。页面上只有一个按钮。使用“btnAdd_Click”事件并调用“CreateChildControls”函数。
-
我猜你可以将行存储在
List<>中,在每次点击时向列表中添加一个新项目,然后只渲染该列表中的行。 -
请在我的代码中告诉我你的解决方案......带有答案......