将datagridview保存到csv时的System.String []

时间:2015-04-10 09:58:42

标签: vb.net csv file-io datagridview

此代码将datagrid视图转换为csv文件。 这段代码运行正常......但是当升级到VS 2013时它停止运行...在我的Test2.txt文件中保持重新调整System.String [] ..

Dim path As String = "D:\Test2.txt"
        r = -1
        Dim headers = (From header As DataGridViewColumn In Me.DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray()
        Dim rows = From row As DataGridViewRow In Me.DataGridView1.Rows.Cast(Of DataGridViewRow)() _
                   Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
        Using sw As New IO.StreamWriter(path)
            '  MsgBox(String.Join(",", headers))
            sw.WriteLine(String.Join(",", headers))
            For Each r In rows
                sw.WriteLine(String.Join(",", r))
            Next
        End Using

1 个答案:

答案 0 :(得分:0)

以下是将DataGridView内容写入CSV文件的一种方法,我相信您可以根据自己的需要进行调整:

    Dim path As String = "C:\Test2.txt"
    Using sw As New IO.StreamWriter(path)
        Dim rowcontents As New List(Of String)
        For Each col As DataGridViewColumn In DataGridView1.Columns
            rowcontents.Add(col.HeaderText)
        Next
        sw.WriteLine(String.Join(",", rowcontents))
        For Each r As DataGridViewRow In DataGridView1.Rows
            rowcontents.Clear()
            For Each c As DataGridViewCell In r.Cells
                rowcontents.Add(c.Value)
            Next
            sw.WriteLine(String.Join(",", rowcontents))
        Next
    End Using