如何在 C# 中将 DataTable 转换为字符串? [英] How to convert a DataTable to a string in C#?

查看:38
本文介绍了如何在 C# 中将 DataTable 转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Visual Studio 2005 并且有一个包含两列和一些行的数据表,我想输出到控制台.我希望会有类似的东西:

I'm using Visual Studio 2005 and have a DataTable with two columns and some rows that I want to output to the console. I hoped there would be something like:

DataTable results = MyMethod.GetResults();
Console.WriteLine (results.ToString());

将简单的 DataTable 转换为字符串的最佳方法是什么(即我的编码最少)?

What's the best way (i.e. least amount of coding from me) to convert a simple DataTable to a string?

推荐答案

您可以使用类似 这个:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
    Dim sw As System.IO.StringWriter
    Dim output As String

    Console.WriteLine(label)

    ' Loop through each row in the table. '
    For Each row As DataRow In table.Rows
        sw = New System.IO.StringWriter
        ' Loop through each column. '
        For Each col As DataColumn In table.Columns
            ' Output the value of each column's data.
            sw.Write(row(col).ToString() & ", ")
        Next
        output = sw.ToString
        ' Trim off the trailing ", ", so the output looks correct. '
        If output.Length > 2 Then
            output = output.Substring(0, output.Length - 2)
        End If
        ' Display the row in the console window. '
        Console.WriteLine(output)
    Next
    Console.WriteLine()
End Sub

这篇关于如何在 C# 中将 DataTable 转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆