动态Div与表asp.net

时间:2014-02-26 11:59:41

标签: html asp.net vb.net

有没有办法将表格和行添加到动态创建的div元素中?

Dim divTable As New HtmlGenericControl("div")
    divTable.ID = "divTable"
    divTable.Attributes("class") = "printtable"
    divTable.InnerHtml = "<asp:Table ID=""table1"" CellPadding=""1"" runat=""server"">  </asp:Table>"
    divPlaceHolder.Controls.Add(divTable)

我需要向table1添加动态行,但显然每当我尝试从代码文件中访问table1时,就会显示'table1' not declared

帮助!

3 个答案:

答案 0 :(得分:1)

为什么不将Panel(呈现为div)添加到PlaceHolder或仅使用Panel作为容器?您必须将Table作为服务器控件实例添加到该面板。

Dim divTable As New Panel()
divTable.ID = "divTable"
divTable.CssClass = "printtable"
divPlaceHolder.Controls.Add(divTable) ' the placeholder is redundant with a panel '
Dim table As New Table()
table.ID = "table1"
table.CellPadding = 1
divTable.Controls.Add(table) 

您可以通过FindControl找到并访问此表:

Dim divTable As Panel = DirectCast(divPlaceHolder.Controls(0), Panel)
Dim table As Table = DirectCast(divTable.Controls(0), Table)

请记住,您需要在每个回发中重新创建所有动态创建的控件,并且最迟在Page_Load中使用与之前相同的ID。

答案 1 :(得分:0)

当您向动态创建的div`追加String时,它不会。

你的apprach不正确试试这个。

Table table1= new Table();
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "blah blah blah";
row.Cells.Add(cell1);
table1.Rows.Add(row);

答案 2 :(得分:0)

首先,您现有的DIV需要具有runat = server属性。然后你可以从codebehind

调用它
<div id="divRunServer" runat="server"></div>

在codebehind调用中控制并使用Table web ui控件创建动态html元素。

//prepare dynamic table
        Table Table1 = new Table();

        int numrows = 3;
        int numcells = 2;
        for (int j = 0; j < numrows; j++)
        {          
            TableRow r = new TableRow();
            for (int i = 0; i < numcells; i++) {
                TableCell c = new TableCell();
                c.Controls.Add(new LiteralControl("row " 
                    + j.ToString() + ", cell " + i.ToString()));
                r.Cells.Add(c);
            }
            Table1.Rows.Add(r);
        }

//add to div

       divRunServer.Controls.Add(Table1)

Referred from