从datagridview传递空单元格值

时间:2018-07-17 13:01:34

标签: vb.net csv datagridview

我有一个14列的datagridview,大部分情况下都是部分/全部填充数字和字符。

我想做的是将这些值传递到.csv文件中。问题是,我编写的代码没有通过空单元格而崩溃。我希望每个单元格值都用逗号分隔,并且在扫描了该行的所有列后,传递到下一行直到网格的结尾。

数据应如下所示:1945.9,1260.4,P3.P4 ,,,,,,,, 2018-07-17 08:17:27

Datagridview

到目前为止,我的代码如下:

 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim date_rapport As Date = Date.Today
    Format(date_rapport, "dd-MM-yyyy")

    Dim filePath As String = "C:\Rapport_punch" & date_rapport & "\" & ".csv"
    Dim delimeter As String = ","
    Dim sb As New StringBuilder
    For i As Integer = 0 To data_punched.Rows.Count - 1
        Dim array As String() = New String(data_punched.Columns.Count - 1) {}
        If i.Equals(0) Then
            For j As Integer = 0 To data_punched.Columns.Count - 1
                array(j) = data_punched.Columns(j).HeaderText
            Next
            sb.AppendLine(String.Join(delimeter, array))
        End If
        For j As Integer = 0 To data_punched.Columns.Count - 1
            If Not data_punched.Rows(i).IsNewRow Then
                array(j) = data_punched(j, i).Value.ToString
            End If
        Next
        If Not data_punched.Rows(i).IsNewRow Then
            sb.AppendLine(String.Join(delimeter, array))
        End If
    Next
    File.WriteAllText(filePath, sb.ToString)
    'Opens the file immediately after writing
    Process.Start(filePath)
End Sub

我认为我需要处理代码的这一部分,但不知道如何做。

 For j As Integer = 0 To data_punched.Columns.Count - 1
            If Not data_punched.Rows(i).IsNewRow Then
                array(j) = data_punched(j, i).Value.ToString
            End If
 Next

任何想法

1 个答案:

答案 0 :(得分:1)

尝试首先检查它是否为空(因为我在这台机器上没有设置,所以无法检查),这可能是问题所在。

For j As Integer = 0 To data_punched.Columns.Count - 1
        If Not data_punched.Rows(i).IsNewRow Then
            If (data_punched(j, i).Value == null) Then
                array(j) = ""
            Else
                array(j) = data_punched(j, i).Value.ToString
            End If
        End If
 Next