Datatable to html Table

Brad Hazelnut picture Brad Hazelnut · Oct 30, 2013 · Viewed 110.6k times · Source

I have question, that maybe someone here wouldn't mind to help me with. I have lets say 3 datatables, each one of them has the following columns:

size, quantity, amount, duration

Name of datatables and values

LivingRoom
================
1
1
1
1
2
2
2
2

BathRoom
================
3
3
3
3
4
4
4
4

BedRoom
=================
5
5
5
5
6
6
6
6

Now i am trying to build an html invoice to were i can loop through all the datatables and output the following html output, very basic:

<table>
  <tr>
    <td>Area</td>
  </tr>
  <tr>
    <td>Living Room</td>
  </tr>

  <tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
  </tr>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>2</td>
    <td>2</td>
    <td>2</td>
  </tr>

  <tr>
    <td>Area</td>
  </tr>
  <tr>
    <td>Bathroom</td>
  </tr>

  <tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
  </tr>
  <tr>
    <td>3</td>
    <td>3</td>
    <td>3</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>4</td>
    <td>4</td>
    <td>4</td>
  </tr>

  <tr>
    <td>Area</td>
  </tr>
  <tr>
    <td>Bedroom</td>
  </tr>

  <tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
  </tr>
  <tr>
    <td>5</td>
    <td>5</td>
    <td>5</td>
    <td>5</td>
  </tr>
  <tr>
    <td>6</td>
    <td>6</td>
    <td>6</td>
    <td>6</td>
  </tr>
</table>

So pretty much the area would have the name of the datatable, and then under each area loop that specific datatable and output the datat in that format. I can't figure out the looping logic or how to do this, i've been breaking my head for the last few days on this. maybe i'm just thinking about it in the wrong way but i could really use some help on this.

Answer

Omer Eldan picture Omer Eldan · Oct 30, 2013

use this function:

    public static string ConvertDataTableToHTML(DataTable dt)
    {
        string html = "<table>";
        //add header row
        html += "<tr>";
        for(int i=0;i<dt.Columns.Count;i++)
            html+="<td>"+dt.Columns[i].ColumnName+"</td>";
        html += "</tr>";
        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j< dt.Columns.Count; j++)
                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";
        return html;
    }