Search code examples
asp.nethtmlsqlsql-serverdatarepeater

How to make a comparison html table using asp repeater (data rotation)


I need to make a comparison table in HTML format, the problem is that the items in database comes as a columns but in comparison table it must be a rows!

Example

The data in database looks like the following

 ID  Name     Color   Weight
-------------------------------
 1   Ball     Red     10
 2   Table    Black   50
 3   Chair    Green   30

And it must looks like the following in comparison table

ID      1         2        3
Name    Ball      Table    Chair
Color   Red       Black    Green
Weight  10        50       30

I am using ASP.NET with repeater but it didn't work, Can you please help me to find the best way to do this.

I must use something like repeater because the numbers of columns in the the comparison table varies.


Solution

  • A possible solution:

    Given the following DataTable as datasource:

    protected DataTable Data
    {
        get
        {
            if (ViewState["Data"] == null)
            { 
                DataTable table = new DataTable();
                table.Columns.Add("ID", typeof(int));
                table.Columns.Add("Name");
                table.Columns.Add("Color");
                table.Columns.Add("Weight", typeof(int));
    
                table.Rows.Add(1, "Ball", "Red", 10);
                table.Rows.Add(2, "Table", "Black", 50);
                table.Rows.Add(3, "Chair", "Green", 30);
                ViewState["Data"] = table;
            }
            return (DataTable)ViewState["Data"];
        }
    }
    

    And some ASP code for looping and building the table:

    <table>
    <%
      for (int i = 0; i < Data.Columns.Count; i++)
      {
            %>
            <tr>
                <td><%= Data.Columns[i].ColumnName %></td>
                <%
                    for (int j = 0; j < Data.Rows.Count; j++)
                    {
                        %>
                        <td><%= Data.Rows[j][i] %></td>
                        <%
                    }
    
                 %>
            </tr>
            <%  
      } 
    %>
    </table>