ASP.NET:将DataTable呈现为字符串(HTML)的最短方法? [英] ASP.NET: Shortest way to render DataTable to a string (HTML)?
问题描述
将DataTable转换为字符串(格式为HTML)的最短方法是什么?
What is the shortest way to convert a DataTable into a string (formatted in HTML)?
以编程方式绑定到UI控件并呈现到ASP.NET页是不可接受的。不能依赖于ASP.NET页面生命周期。
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.
此目的无关紧要,但要满足好奇心:这是为了进行大量DataTable处理的算法中的记录/调试/转储目的。
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.
谢谢!
推荐答案
您可以使用ASP.net控件,例如GridView,DataGrid并使用StringWriter将其渲染到StringBuilder中,无需为此使用ASP.net页,这是控制台中的简单示例
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; }
}
这篇关于ASP.NET:将DataTable呈现为字符串(HTML)的最短方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!