[c#] Datatable to html Table

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.

This question is related to c# asp.net datatable

The answer is


public static string toHTML_Table(DataTable dt)
{
    if (dt.Rows.Count == 0) return ""; // enter code here

    StringBuilder builder = new StringBuilder();
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("Page-");
    builder.Append(Guid.NewGuid());
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    builder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn c in dt.Columns)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(c.ColumnName);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");
    foreach (DataRow r in dt.Rows)
    {
        builder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn c in dt.Columns)
        {
            builder.Append("<td align='left' valign='top'>");
            builder.Append(r[c.ColumnName]);
            builder.Append("</td>");
        }
        builder.Append("</tr>");
    }
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

From this link

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;

namespace ClientUtil
{
public class DataTableUtil
{

public static string DataTableToXmlString(DataTable dtData)
{
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(“<TABLE>”);
stringBuilder.Append(“<TR>”);
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
else
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
}
stringBuilder.Append(“</TR>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
{
stringBuilder.Append(“<TR>”);
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “&lt;”).Replace(“>”, “&gt;”).Replace(“\””, “&quot;”).Replace(“‘”, “&apos;”).Replace(“&”, “&amp;”);
if (!string.IsNullOrEmpty(str))
stringBuilder.Append(“<TD>”).Append(str).Append(“</TD>”);
else
stringBuilder.Append(“<TD>”).Append(“</TD>”);
++num2;
}
stringBuilder.Append(“</TR>”);
++num1;
}
stringBuilder.Append(“</TABLE>”);
return ((object) stringBuilder).ToString();
}

protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
{
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
{
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
}
return false;
}

public static DataTable XmlStringToDataTable(string XmlData)
{
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
xmlDocument2.LoadXml(XmlData);
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
{
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
{
if (num == 0)
{
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
{
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
{
if (!bool.TryParse(str, out result))
result = false;
}
else
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
list.Add(column);
if (!dataTable.Columns.Contains(column.ColumnName))
dataTable.Columns.Add(column);
}
if (list.Count > 0)
{
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
}
}
else
{
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
{
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
{
try
{
s = s.Replace(“&lt;”, “<“);
s = s.Replace(“&gt;”, “>”);
s = s.Replace(“&quot;”, “\””);
s = s.Replace(“&apos;”, “‘”);
s = s.Replace(“&amp;”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
}
catch
{
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
}
}
else
row[index] = Convert.DBNull;
++index;
}
dataTable.Rows.Add(row);
}
++num;
}
}
return dataTable;
}
}
}

Since I didn't see this in any of the other answers, and since it's more efficient (in lines of code and in speed), here's a solution in VB.NET using a stringbuilder and lambda functions with String.Join instead of For loops for the columns.

Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
    sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")

You can add your own styles to this pretty easily.


As per my understanding you need to show 3 tables data in one html table using asp.net with c#.

I think best you just create one dataset with 3 DataTable object.

Bind that dataset to GriView directly on page load.


The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden

Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.

This is my sample code:

private string MakeHtmlTable(DataTable data)
{
            string[] table = new string[data.Rows.Count] ;
            long counter = 1;
            foreach (DataRow row in data.Rows)
            {
                table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";

                counter+=1;
            }

            return "</br><table>" + String.Join("", table) + "</table>";
}

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

The controller might look something like this.

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

Hope this helps :)


I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

why this solution? Because you can easily just add this to a panel ie:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

and your solution would look something like:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

interpret the rest, and have fun.


Just in case anyone arrives here and was hoping for VB (I did, and I didn't enter c# as a search term), here's the basics of the first response..

Public Shared Function ConvertDataTableToHTML(dt As DataTable) As String
    Dim html As String = "<table>"
    html += "<tr>"
    For i As Integer = 0 To dt.Columns.Count - 1
        html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Columns(i).ColumnName) + "</td>"
    Next
    html += "</tr>"
    For i As Integer = 0 To dt.Rows.Count - 1
        html += "<tr>"
        For j As Integer = 0 To dt.Columns.Count - 1
            html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Rows(i)(j).ToString()) + "</td>"
        Next
        html += "</tr>"
    Next
    html += "</table>"
    Return html
End Function

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to datatable

Can't bind to 'dataSource' since it isn't a known property of 'table' How to get a specific column value from a DataTable in c# Change Row background color based on cell value DataTable How to bind DataTable to Datagrid Find row in datatable with specific id Datatable to html Table How to Edit a row in the datatable How do I use SELECT GROUP BY in DataTable.Select(Expression)? How to fill a datatable with List<T> SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column