Technical Implementation of Generating Structured HTML Tables from C# DataTables

Dec 11, 2025 · Programming · 11 views · 7.8

Keywords: DataTable | HTML | C# | ASP.NET | LoopingLogic

Abstract: This paper explores how to convert multiple DataTables into structured HTML tables in C# and ASP.NET environments for generating documents like invoices. By analyzing the DataTable data structure, a method is provided to loop through multiple DataTables and add area titles, extending the function from the best answer, and discussing code optimization and practical applications.

Problem Background

In ASP.NET development, it is often necessary to convert data from DataTables to HTML format for display on web pages. A common issue users face is having multiple DataTables, each representing different areas (e.g., living room, bathroom, bedroom), with each DataTable having the same column structure (size, quantity, amount, duration). The goal is to generate an HTML table that first lists area names and then displays data rows for each area.

Overview of DataTable Data Structure

DataTable is a class in the System.Data namespace used to store data in tabular form. It consists of columns (Columns) and rows (Rows), where columns define the data structure and rows contain actual values. In C#, DataTables are commonly used for database query results or in-memory data storage.

Single DataTable to HTML Conversion

Based on the best answer, a static function can be used to convert a single DataTable to an HTML table. The core logic of the function involves looping through columns and rows to build an HTML string.

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 data 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;
}

This function first generates the <table> tag, then adds a header row (column names), followed by looping through each row to add data rows. However, the user's requirement involves multiple DataTables, so this logic needs to be extended.

Extension: Handling Multiple DataTables

To handle multiple DataTables, we can modify the function or create a new one that loops through a list of DataTables and adds area titles for each. Assume we have a list of DataTables, each with a name property (or identified in another way).

public static string ConvertDataTablesToHTML(List<DataTable> dataTables, List<string> areaNames)
{
    if (dataTables.Count != areaNames.Count)
        throw new ArgumentException("Number of DataTables and area names do not match");
    
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("<table>");
    
    for (int k = 0; k < dataTables.Count; k++)
    {
        DataTable dt = dataTables[k];
        string areaName = areaNames[k];
        
        // Add area title rows
        htmlBuilder.Append("<tr><td>Area</td></tr>");
        htmlBuilder.AppendFormat("<tr><td>{0}</td></tr>", areaName);
        
        // Add data header
        htmlBuilder.Append("<tr>");
        for (int i = 0; i < dt.Columns.Count; i++)
            htmlBuilder.AppendFormat("<td>{0}</td>", dt.Columns[i].ColumnName);
        htmlBuilder.Append("</tr>");
        
        // Add data rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            htmlBuilder.Append("<tr>");
            for (int j = 0; j < dt.Columns.Count; j++)
                htmlBuilder.AppendFormat("<td>{0}</td>", dt.Rows[i][j].ToString());
            htmlBuilder.Append("</tr>");
        }
    }
    
    htmlBuilder.Append("</table>");
    return htmlBuilder.ToString();
}

This function accepts a list of DataTables and corresponding area names, loops through each DataTable, first adds "Area" title and area name, then adds the data. StringBuilder is used to improve performance by avoiding string concatenation overhead.

Code Analysis and Optimization

The original function uses string concatenation, which can cause performance issues with large data. The improved version uses StringBuilder, which is the recommended approach for string manipulation. Additionally, the function assumes DataTables have the same column structure; if columns differ, header generation logic may need adjustment. Error handling is added to ensure the number of DataTables and names match.

In practical ASP.NET applications, this function can be integrated into page code to dynamically generate HTML and output to the response stream. For example, call the function in a button click event and set the Text property of a Literal control.

Practical Applications and Conclusion

By extending the single DataTable conversion logic, we can effectively handle multiple DataTables to generate structured HTML tables suitable for invoices, reports, and other scenarios. This method simplifies front-end rendering and allows flexible control over data presentation in backend C# code. Future improvements may include support for CSS styling, dynamic column sorting, or pagination features.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.