views:

1147

answers:

4

What is the shortest way to convert a DataTable into a string (formatted in HTML)?

Programmatically binding to a UI control and rendering to an ASP.NET page is not acceptable. Can't depend on the ASP.NET page lifecycle.

The purpose of this shouldn't matter, but to satisfy curiosity: This is for logging/debugging/dump purposes in algorithms that do a lot of DataTable processing.

Thanks!

+1  A: 

Create the control, create an HTML Writer, set any settings or databind the control, then call the render method, using the HTML Writer.

You can then get the string out of the writer.

Edit: I initially misread the question and thought you wanted to render a datagrid.

A Datatable can easily be rendered to its XML.

you asked for HTML.

here is a console app code that will render a datatable using a datagrid control.

class Program
{
 static void Main(string[] args)
 {
  DataTable dt = new DataTable();
  dt.Columns.Add("Column1");
  dt.Columns.Add("Column2");
  dt.Rows.Add("RowValue1", "Field2RowValue1");
  dt.Rows.Add("RowValue2", "Field2RowValue2");

  DataGrid dg = new DataGrid();
  dg.DataSource = dt;
  dg.DataBind();

  StringWriter sw = new StringWriter();
  HtmlTextWriter w = new HtmlTextWriter(sw);

  dg.RenderControl(w);

  Console.Write(sw.ToString());
  Console.ReadLine();
 }
}
Jeff Martin
+7  A: 

You can use the ASP.net controls such as GridView, DataGrid and point them render into StringBuilder using StringWriter, No need to use ASP.net page for this, this is a simple example in Console

class Program
{
    static void Main(string[] args)
    {
        IList<Person> persons = new List<Person>()
            {
               new Person{Id = 1, Name="Test Name 1"},
               new Person{Id = 2, Name="Test Name 2"}
            };

        GridView gridView = new GridView();
        StringBuilder result =  new StringBuilder();
        StringWriter writer = new StringWriter(result);
        HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
        gridView.DataSource = persons;
        gridView.DataBind();

        gridView.RenderControl(htmlWriter);

        Console.WriteLine(result);
    }


}


class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}
bashmohandes
+4  A: 

I use this function through my application. It's pretty straightforward

  static public string ConvertDataTableToHTMLString(System.Data.DataTable dt, string filter, string sort, string fontsize, string border, bool headers, bool useCaptionForHeaders)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='" + border + "'b>");
            if (headers)
            {
                //write column headings
                sb.Append("<tr>");
                foreach (System.Data.DataColumn dc in dt.Columns)
                {
                    if (useCaptionForHeaders)
                        sb.Append("<td><b><font face=Arial size=2>" + dc.Caption + "</font></b></td>");
                    else
                        sb.Append("<td><b><font face=Arial size=2>" + dc.ColumnName + "</font></b></td>");
                }
                sb.Append("</tr>");
            }

            //write table data
            foreach (System.Data.DataRow dr in dt.Select(filter,sort))
            {
                sb.Append("<tr>");
                foreach (System.Data.DataColumn dc in dt.Columns)
                {
                    sb.Append("<td><font face=Arial size=" + fontsize + ">" + dr[dc].ToString() + "</font></td>");
                }
                sb.Append("</tr>");
            }
            sb.Append("</table>");

            return sb.ToString();
        }
Cody C
I used this same approach even for reasonably large tables 10,000+ records.
garykindel
+2  A: 

If this is just for purposes of logging, might it not make more sense to log them out as XML - easier to manipulate if you need to. You just need to call the WriteXml method.

Paddy