I have a DataGridView where I save the values to a CSV file. The code creates an empty value in the CSV where there is an empty cell in the DataGridView. The problem I have is with Column 10 in the DataGridView. This is a CheckBox column. The value of this column is “Nothing” unless it has been either checked or unchecked in which case the value becomes 0 or 1 (False or True).
When I load the CSV back into the DataGridView, if there is an empty value for the CheckBox Column I get an error. The DataGridView does not accept a “Nothing” value for this Column when importing from a CSV.
Is there a way to export the value of Column 10 only as 0 or 1?
Hoping someone can help me resolve this problem. Thanks in advance.
This is the code I use to Save the DataGridView to a CSV file.
Dim rows = From row As DataGridViewRow In 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)
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
End Using
And this is the code I use to load the CSV back into the DataGridView.
Try
Dim streamReader As IO.StreamReader = New IO.StreamReader(FullPath)
'Read CSV file content
While streamReader.Peek() <> -1
rowvalue = streamReader.ReadLine()
cellvalue = rowvalue.Split(","c)
DataGridView1.Rows.Add(cellvalue)
End While
streamReader.Close()
Catch ex As Exception
MsgBox("File not found")
End Try
If you don't want any empty values in that column then don't allow any. The simplest option for that is to set Value
of the cell in that column to False
when a row is added, if it's not already set to something else:
Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
Dim cell = DataGridView1.Rows(e.RowIndex).Cells(checkBoxColumnIndex)
Dim value = cell.Value
If value Is Nothing Then
cell.Value = False
End If
End Sub
With that, False
effectively becomes the default value for that column. All your existing export and import code will just work.