问题
How can I loop through a datatable so that the rows display neatly underneath one another,row by row.
what I have tried is the following but like this all the data displays in one column.
foreach (DataRow row in myTopTenData.Rows)
{
foreach (DataColumn col in myTopTenData.Columns)
{
Console.Write(row[col].ToString() + " ");
Console.WriteLine();
}
}
回答1:
foreach (DataRow row in myTopTenData.Rows)
{
foreach (DataColumn col in myTopTenData.Columns)
Console.Write(string.Format("{0, -10}", row[col].ToString()));
Console.WriteLine();
}
string.Format"{0, -10}" will help you to align your columns (use negative values for a left alignment, positive for a right alignement, and of course 10 is an arbitrary value).
回答2:
You can use this little Linq query and String.Join:
var allFields = myTopTenData.AsEnumerable()
.Select(r => string.Join(Environment.NewLine, r.ItemArray));
string allFieldsLines = string.Join(Environment.NewLine, allFields);
Console.Write(allFieldsLines);
Here's the non-Linq version with a loop:
foreach (DataRow row in myTopTenData.Rows)
Console.Write(string.Join(Environment.NewLine, row.ItemArray) + Environment.NewLine);
回答3:
Why don't you just try with this:
foreach (DataRow row in myTopTenData.Rows)
{
foreach (DataColumn col in myTopTenData.Columns)
{
Console.Write(row[col].ToString() + " ");
}
Console.WriteLine();
}
来源:https://stackoverflow.com/questions/14376412/displaying-datarows-underneath-each-other