Adding rows dynamically to a HTML table

19,905

Solution 1

It's been a while but there is the repeater-control in ASP.NET Webforms for this kind of stuff.

Here is a nice article introducing this conept: Data Repeater Controls in ASP.NET

I think this will be easier for you than hacking this with AJAX/JScript

Aside from this: Daniel Casserly is right - this is very easy if you do it in MVC (even easier if you use Razor-Syntax), as it would translate do something like:

<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            ... whatever you need here ...
        </tr>
    }
</table>

Solution 2

you can give it an Id and Set runat="server" attribute and use it from code behind using Id you gave it

System.Web.UI.HtmlControls.HtmlTableRow r=new System.Web.UI.HtmlControls.HtmlTableRow();
            System.Web.UI.HtmlControls.HtmlTableCell c = new System.Web.UI.HtmlControls.HtmlTableCell();
            c.InnerText = "New Cell";
            r.Cells.Add(c);
            T.Rows.Add(r);

where T is the Id of your table

Solution 3

You can do this with JQuery but for that you will need to give and Id or class or just search for the table array and then inject rows to it

Share:
19,905
Saiesh
Author by

Saiesh

Updated on June 13, 2022

Comments

  • Saiesh
    Saiesh about 2 years

    I have a asp.net web site that contains some tables. However these are not asp:Table i.e. they are simple HTML tables built this way:

     <table><tr><td></td></tr></table> 
    

    Now I would like to know if it's possible to add rows dynamically to this table from the code behind (i.e. C#) and if yes, how do I go about doing it?

  • Saiesh
    Saiesh almost 12 years
    Oh yes , an ID can definitely be given . Is there any way i can do it without using JQuery ?
  • Daniel Casserly
    Daniel Casserly almost 12 years
    I knew somebody less lazy than me would write the Razor code. Thanks Carsten :-)
  • Saiesh
    Saiesh almost 12 years
    How do i add the css class to be associated with each row or element ? There seems to be no functionality to do that for these row and cell elements .
  • Maha Khairy
    Maha Khairy almost 12 years
    there is Cell.style property I guess this is where styles are added, I never tried it though