ASP.NET后台动态添加一个Table控件。后面用FindControl找不到它并且没提示错误,接收新控件的新实例Table显示值为NULL。
题目写的很清楚。代码如下。
for (int i = 1; i <= this.ListBox1.Items.Count; i++)
{
Table autoTable = new Table(); //初始化表
this.Page.Controls.Add(autoTable);
autoTable.ID = i.ToString(); //
autoTable.CssClass = "table";
Response.Write(autoTable.ID);
}
这是动态添加多个表,并且设置了ID属性,便于后边findcontrol。
for (int i = ListBox1.Items.Count; i <= ListBox1.Items.Count; i++)
{
int indexItem = this.ListBox1.Items.IndexOf(this.ListBox1.Items.FindByText(last.GetValue(5).ToString()));
Table mytable = (Table)FindControl((indexItem + 1).ToString());
TableRow rows = new TableRow();
rows.Cells.Add(tCell);
mytable.Rows.Add(rows);
Response.Write(mytable.ID);
}
这是后边找到这个控件并且赋值添加cell和rows的。但是提示未将对象引用到实例。跟踪单步之后发现。
mytable值为NULL,也就是未找到控件。但是为什么不报错呢?
还有运行之后竟然把值都加到一个表里边了。
我生成的三个表只有一个用上了。