从后面的代码填充div表

时间:2015-09-15 12:26:51

标签: c# asp.net

尝试使用表格从后面的代码动态填充div,并且每次循环循环时向表中添加另一行....

Table table = new Table();
            table.ID = "Table1";
            mapInnerDiv.Controls.Add(table);

            foreach (Layer l in Layers)
            {
                string splitURL = l.URL.Split('/')[7];

                TableRow row = new TableRow();
                TableCell cell = new TableCell();

                TextBox tb = new TextBox();

                tb.ID = splitURL;

                    // Add the control to the TableCell
                    cell.Controls.Add(tb);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);
            }

上面的代码没有填充div。从控制台我可以看到一个表被添加到div,但它是空的。 添加到诸如mapInnerDiv.InnerHtml = "this is a text post"; 之类的innerHTML将显示此消息,但如果我使用标记并尝试从此处添加到div,则在添加新行时将会很困难吗?

关于我的循环出错的任何想法,谢谢

2 个答案:

答案 0 :(得分:0)

您的代码需要重新安排,您需要将行添加到表中。

Table table = new Table();
table.ID = "Table1";

foreach (Layer l in Layers)
    {
    string splitURL = l.URL.Split('/')[7];

    TableRow row = new TableRow();
    TableCell cell = new TableCell();
    TextBox tb = new TextBox();
    tb.ID = splitURL;
    // Add the control to the TableCell
    cell.Controls.Add(tb);
    // Add the TableCell to the TableRow
    row.Cells.Add(cell);
    table.Rows.Add(row);
    }
mapInnerDiv.Controls.Add(table);

在完全构建完毕后,将表添加到div中。

并确保mapInnerDiv定义如下:

<div id="mapInnerDiv" runat="server"></div>

答案 1 :(得分:0)

  

我可以看到一个表被添加到div中,但它是空的

这是因为没有行添加到您的表中。

添加以下代码table.Rows.Add(row),将该行添加到此行下方的table

row.Cells.Add(cell);

相关问题