Search code examples
c#asp.nethtmlgenericcontrol

Create X tables by looping with HtmlGenericControl


I'm trying to create 10 different tables, but I only end up with a single one.

HtmlGenericControl table = new HtmlGenericControl("table");
for (int i = 1; i < 5; i++)
{
    table.ID = "Serie_table_" + i;
    table.Attributes.Add("class", "Serie_table");
    divSerie_lists.Controls.Add(table);
}

I would like the following result:

<table id="Serie_table_1" class="Serie_table">
<table id="Serie_table_2" class="Serie_table">
<table id="Serie_table_3" class="Serie_table">
<table id="Serie_table_4" class="Serie_table">

But I end up with this:

<table id="Serie_table_4" class="Serie_table"/>

I hope you can help me loop though - and create the tables correctly.


Solution

  • You change the same object 4 times. Instead you need to create 4 different objects:

    for (int i = 1; i < 5; i++)
    {
        HtmlGenericControl table = new HtmlGenericControl("table");
        table.ID = "Serie_table_" + i;
        table.Attributes.Add("class", "Serie_table");
        divSerie_lists.Controls.Add(table);
    }
    

    Also you can use HtmlTable rather than HtmlGenericControl.