C# writing data to HTML table

I am programming in C#. I have some data that I want to write to an HTML file as a table of 3 columns and an unknown number of rows.

Then I display that file in a web browser.

Currently this is all done by brute force. The C# code writes out the <HTML> tag and all the following header tags. It writes the <TABLE> tag. It loops through the data, writing each line of the table, adding appropriate <TR>...</TR> and <TD>...</TD> tags. It then closes the table with a </TABLE> tag, writes some footer information, and finally ends the file with a </HTML> tag.

There's got to be a better way.

This code works, but it's difficult to maintain.

I know PHP has a nice way of dealing with this, But I'm not using PHP, I'm using C#.

I've seen XSLT transformations that outputs nice HTML code, but my input isn't XML.

Is there a good way to deal with this in C#? Where I can create some sort of template that's easy to understand and maintain? A template that conveys the idea, "I want the output to be a HTML file which has a table of 3 columns"?
deleydSoftware EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
There's got to be a better way.
for web development in C# (ASP.NET), you can refer to controls: GridView or Repeater
Kyle AbrahamsSenior .Net DeveloperCommented:
You could just use a <asp:GridView> and bind the source of the input to the grid.

https://msdn.microsoft.com/en-us/library/aa479342.aspx
Dirk StraussSenior Full Stack DeveloperCommented:
The ASP.NET GridView is a great solution. I did however once have a requirement to export the C# DataTable object to an HTML table which was then used as a printer friendly and export to PDF page. This is the method I used (which I modified slightly) if memory serves me right. This is a good basis to start from though.

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

Open in new window


What I'm getting at is sometimes an ASP.NET DataGrid is not required. Representing data in a grid form on a web page is almost always done inside a repeating control such as a Repeater or GridView. For edge cases (where the standard .NET controls wont work), outputting to an HTML table is the next best thing.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

deleydSoftware EngineerAuthor Commented:
Well I'm not using ASP.NET. I'm just using C# and WPF.

It's currently done by brute force. I'm hoping there's a more elegant solution.

Thank you!
Kyle AbrahamsSenior .Net DeveloperCommented:
For WPF you can use a datagrid:
http://www.wpftutorial.net/datagrid.html
Dustin SaundersDirector of OperationsCommented:
This code works, but it's difficult to maintain.

How so?

You can get some really well designed tables using bootstrap and jquery, but you'll need to do this HTML assembly to do so.  That being said, why is it difficult to maintain?  You can write one method to build a table for any select result.  I haven't had an opportunity to test run this, but as an example:

static string TableBuilder(DataTable dataTable)
        {
            string html = @"
                <table>
                    <thead>
                        <tr>
                        {0}
                        </tr>
                    </thead>
                    <tbody>
                        {1}
                    </tbody>
                </table>";

            string headers = string.Empty;
            string body = string.Empty;

            foreach (DataColumn dc in dataTable.Columns)
            {
                headers += "\n<td>" + dc.ColumnName + "</td>";
            }

            foreach (DataRow dr in dataTable.Rows)
            {
                body += "\n<tr>";

                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    body += "\n<td>" + dr[i].ToString() + "</td>";
                }

                body += "</tr>";
            }

            return string.Format(html, headers, body);
        }

Open in new window


You can pass in any DataTable this way and get an HTML result, nothing to maintain.  Add in whatever other features you want (pass in class tags, etc.)
Dustin SaundersDirector of OperationsCommented:
FYI check this link:  https://datatables.net/

This jquery datatable class has nice functionality- with built in search, pagination, per page display, and sort.
Dirk StraussSenior Full Stack DeveloperCommented:
Hi deleyd

Well I'm not using ASP.NET. I'm just using C# and WPF.

It's currently done by brute force. I'm hoping there's a more elegant solution.

If you are not using ASP.NET, then modify your topics selected for this question. It lists ASP.NET.
Incorrect topic

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
deleydSoftware EngineerAuthor Commented:
Oh my thank you for pointing that out! I didn't know EE somehow added ASP.NET to the list.

I decided my real problem was separation of responsibilities. It's all intertwined the fetching to data and the formatting with HTML. The formatting is spread all over the program. I need to consolidate that so the formatting is in one place, and the fetching of data is a separate responsibility.

Thank you everyone for the help I greatly appreciate it, and sorry for the ASP.NET tag that somehow got in there.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.