ASP.NET: Shortest way to render DataTable to a string (HTML)?
asp.net, datatable, string
Solution
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; }
}
Problem
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!