Displaying datarows underneath each other

北慕城南 提交于 2019-12-13 06:43:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!