C# 打印数据表的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15547959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:08:18  来源:igfitidea点击:

Print Contents Of A DataTable

c#sql-serverdatatable

提问by William

Currently I have code which looks up a database table through a SQL connection and inserts the top five rows into a Datatable (Table).

目前我有通过 SQL 连接查找数据库表并将前五行插入数据表(表)的代码。

using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
    DataTable Table = new DataTable("TestTable");

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _con.Open();
    _dap.Fill(Table);
    _con.Close();
}

How do I then print the contents of this table to the console for the user to see?

然后我如何将此表的内容打印到控制台以供用户查看?

After digging around, is it possible that I should bind the contents to a list view, or is there a way to print them directly? I'm not concerned with design at this stage, just the data.

在挖掘之后,我是否可以将内容绑定到列表视图,或者有没有办法直接打印它们?在这个阶段我不关心设计,只关心数据。

Any pointers would be great, thanks!

任何指针都会很棒,谢谢!

采纳答案by Arshad

you can try this code :

你可以试试这个代码:

foreach (DataRow dataRow in Table.Rows)
  {
   foreach (var item in dataRow.ItemArray)
   {
    Console.WriteLine(item);
   }
  }

Update 1

更新 1

 DataTable Table = new DataTable("TestTable");
 using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
    {        
       SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
       _con.Open();
       _dap.Fill(Table);
       _con.Close();

      }
 Console.WriteLine(Table.Rows.Count);  
 foreach (DataRow dataRow in Table.Rows)
      {
       foreach (var item in dataRow.ItemArray)
       {
        Console.WriteLine(item);
       }
      }

回答by Russell Gantman

Here is another solution which dumps the table to a comma separated string:

这是将表转储为逗号分隔字符串的另一种解决方案:

using System.Data;

public static string DumpDataTable(DataTable table)
        {
            string data = string.Empty;
            StringBuilder sb = new StringBuilder();

            if (null != table && null != table.Rows)
            {
                foreach (DataRow dataRow in table.Rows)
                {
                    foreach (var item in dataRow.ItemArray)
                    {
                        sb.Append(item);
                        sb.Append(',');
                    }
                    sb.AppendLine();
                }

                data = sb.ToString();
            }
            return data;
        }

回答by Sameer Bahad

Print Datatable contents rows with column

打印带有列的数据表内容行

Here is solution 

DataTable datatableinfo= new DataTable();

// Fill data table 

//datatableinfo=fill by function or get data from database

//Print data table with rows and column


for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
    for (int i = 0; i < datatableinfo.Columns.Count; i++)    
        {    
            Console.Write(datatableinfo.Columns[i].ColumnName + " ");    
            Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]); 
        }
}


Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value

回答by Veer Jangid

This is done by data table that holds single table

这是由包含单个表的数据表完成的

        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from info", con);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();
        ad.Fill(dt);
        Console.WriteLine(dt.Columns[0].ColumnName.ToString());
        Console.WriteLine(dt.Rows[1].ItemArray[0].ToString());

This is done by data set that holds set of table

这是由包含一组表的数据集完成的

        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from info", con);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);

        DataSet dt = new DataSet();
        ad.Fill(dt);
        Console.WriteLine(dt.Tables[0].Columns[0].ColumnName.ToString());
        Console.WriteLine(dt.Tables[0].Rows[0].ItemArray[0].ToString());

both will give same result. only data set contains number of index of table.

两者都会给出相同的结果。只有数据集包含表的索引数。

回答by Tawab Wakil

Building on another answer here, here's a method that converts a DataTable to CSV output and adds the column names as the first row in the output:

基于此处的另一个答案,这是一种将 DataTable 转换为 CSV 输出并将列名称添加为输出中的第一行的方法:

public static string DataTableToCsv(DataTable table)
{
    string result = string.Empty;
    StringBuilder resultBuilder = new StringBuilder();

    if (table != null && table.Rows != null && table.Columns != null && table.Columns.Count > 0)
    {
        int lastItemIndex = table.Columns.Count - 1;
        int index = 0;

        foreach (DataColumn column in table.Columns)
        {
            resultBuilder.Append(column.ColumnName);

            if (index < lastItemIndex)       // if not the last element in the row
                resultBuilder.Append(", ");  // add the separator

            index++;
        }

        resultBuilder.AppendLine();  // add a CRLF after column names row

        foreach (DataRow dataRow in table.Rows)
        {
            lastItemIndex = dataRow.ItemArray.Length - 1;
            index = 0;

            foreach (object item in dataRow.ItemArray)
            {
                resultBuilder.Append(item);

                if (index < lastItemIndex)       // if not the last element in the row
                    resultBuilder.Append(", ");  // add the separator

                index++;
            }

            resultBuilder.AppendLine();  // add a CRLF after each data row
        }

        result = resultBuilder.ToString();
    }

    return result;
}

Usage example:

用法示例:

DataTable table = new DataTable();
....
Console.WriteLine(DataTableToCsv(table));

Note that this method does not properly handle (i.e., escape) data that contains quotes or commas. But it should be sufficient as a quick and dirty way to dump a data table to the console or anywhere else for viewing.

请注意,此方法无法正确处理(即转义)包含引号或逗号的数据。但是,作为将数据表转储到控制台或其他任何地方以供查看的快速而肮脏的方式,它应该足够了。