How to convert a DataTable to a string in C#?
Late but this is what I use
public static string ConvertDataTableToString(DataTable dataTable)
{
var output = new StringBuilder();
var columnsWidths = new int[dataTable.Columns.Count];
// Get column widths
foreach (DataRow row in dataTable.Rows)
{
for(int i = 0; i < dataTable.Columns.Count; i++)
{
var length = row[i].ToString().Length;
if (columnsWidths[i] < length)
columnsWidths[i] = length;
}
}
// Get Column Titles
for (int i = 0; i < dataTable.Columns.Count; i++)
{
var length = dataTable.Columns[i].ColumnName.Length;
if (columnsWidths[i] < length)
columnsWidths[i] = length;
}
// Write Column titles
for (int i = 0; i < dataTable.Columns.Count; i++)
{
var text = dataTable.Columns[i].ColumnName;
output.Append("|" + PadCenter(text, columnsWidths[i] + 2));
}
output.Append("|\n" + new string('=', output.Length) + "\n");
// Write Rows
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
var text = row[i].ToString();
output.Append("|" + PadCenter(text,columnsWidths[i] + 2));
}
output.Append("|\n");
}
return output.ToString();
}
private static string PadCenter(string text, int maxLength)
{
int diff = maxLength - text.Length;
return new string(' ', diff/2) + text + new string(' ', (int) (diff / 2.0 + 0.5));
}
Prerequisite
using System.Linq;
then ...
string res = string.Join(Environment.NewLine,
results.Rows.OfType<DataRow>().Select(x => string.Join(" ; ", x.ItemArray)));
using(var writer = new StringWriter()) {
results.WriteXml(writer);
Console.WriteLine(writer.ToString());
}
Of course the usefulness of this depends on how important the formatting is. If it's just a debug dump, I find XML outputs like this very readable. However, if the formatting is important to you, then you have no choice but to write your own method to do it.