Reputation:
How can I dynamically create an HTML table or ASP table? I've tried with code below but it's not working.
Table tb = new Table();
tb.ID="tbl"+TBname;
TableRow rowNew = new TableRow();
tb.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
rowNew.Controls.Add(cellNew);
}
I want to create more then one HTML table using loop. How can I do this?
Upvotes: 0
Views: 12706
Reputation: 97
You should avoid trying to create HTML code in C#, either by strings (BAD), or using the ASP.NET Table control (BAD Microsoft)
A much better solution is to type the HTML into the .aspx file and then drop values into it as needed. plus a <% foreach(...) { %> tag to make the rows repeat and you should be good to go.
your code will be far cleaner and nicer to maintain.
Upvotes: 0
Reputation: 3331
As per my comments above (that you say helped you solve the problem), you are not adding the Table
object to the page. Add the following to your code:
Controls.Add(tb);
To create more than one HTML table, just wrap your example code in a for loop, like so:
int tableCount = 2; // Or however many tables you want.
for (int tableIndex = 0; tableIndex < tableCount; tableIndex++)
{
Table tb = new Table();
tb.ID = "tbl" + TBname;
TableRow rowNew = new TableRow();
tb.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
rowNew.Controls.Add(cellNew);
}
}
Upvotes: 0
Reputation: 581
Use literal control say
In Design page:
<asp:Literal id="ltrlctrl1" runat=server />
In Code behind:
ltrlctrl1.Text = "<table><tr><td>your HTML table contents</td></tr></table>";
Refer to: How to: Add Literal Web Server Controls to a Web Forms Page for its dis/advantages.
Upvotes: 1
Reputation: 1288
try this one if you want to create N no. of rows in dynamic HTML table
Front end page
<asp:Literal id="container" runat=server />
Code behind
string Tablecontent='';
int rowCount=10 //change value as per your need
for(int i=1;i<=rowCount;i++){
Tablecontent+="<tr><td>your HTML table contents</td></tr>";
}
container.Text="<table>"+Tablecontent+"</table>";
Upvotes: 0