Reputation: 133
Is there a way to add a table and rows to a dynamically created div
element?
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)
I need to add dynamic rows to table1
but obviously whenever i try to access table1
from the code file it says 'table1' not declared
.
Help !
Upvotes: 0
Views: 2862
Reputation: 460078
Why don't you add a Panel
(which is rendered as a div
) to the PlaceHolder
or use just a Panel
alone as container? You have to add the Table
as server-control instance to that panel.
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)
You can find and access this table via FindControl
:
Dim divTable As Panel = DirectCast(divPlaceHolder.Controls(0), Panel)
Dim table As Table = DirectCast(divTable.Controls(0), Table)
Remember that you need to recreate all dynamically created controls on every postback with the same ID's as before in Page_Load
at the latest.
Upvotes: 2
Reputation: 38683
First of all your existing DIV need to have runat=server property. Then you are able call it from codebehind
<div id="divRunServer" runat="server"></div>
In codebehind call that control and use Table web ui control to create dynamic html element.
//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)
Upvotes: 0
Reputation: 3681
It won't as you are appending a String
to your dynamically created div`.
Your apprach isn't correct try it this way.
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);
Upvotes: 0