Invalid cast exception was unhandled when saving gridview to a file
okay I am totally stuck.
I have been getting some help off and on throughout this project and am anxious to get this problem solved so I can continue on with the rest of this project.
I have a gridview that is set to save to a file, and has the option to import into excel. I keep getting an error of this:
Invalid cast exception was unhandled. At least on开发者_Go百科e element in the source array could not be cast down to the destination array type.
Can anyone tell me in layman easy to understand what this error is speaking of?
This is the code I am trying to use:
Dim fileName As String = ""
Dim dlgSave As New SaveFileDialog
dlgSave.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
dlgSave.AddExtension = True
dlgSave.DefaultExt = "txt"
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
fileName = dlgSave.FileName
SaveToFile(fileName)
End If
End Sub
Private Sub SaveToFile(ByVal fileName As String)
If DataGridView1.RowCount > 0 AndAlso DataGridView1.Rows(0).Cells(0) IsNot Nothing Then
Dim stream As New System.IO.FileStream(fileName, IO.FileMode.Append, IO.FileAccess.Write)
Dim sw As New System.IO.StreamWriter(stream)
For Each row As DataGridViewRow In DataGridView1.Rows
Dim arrLine(9) As String
Dim line As String
**row.Cells.CopyTo(arrLine, 0)**
line = arrLine(0)
line &= ";" & arrLine(1)
line &= ";" & arrLine(2)
line &= ";" & arrLine(3)
line &= ";" & arrLine(4)
line &= ";" & arrLine(5)
line &= ";" & arrLine(6)
line &= ";" & arrLine(7)
line &= ";" & arrLine(8)
sw.WriteLine(line)
Next
sw.Flush()
sw.Close()
End If
I bolded the line where it shows in debug, and I really dont see what all the fuss is about LOL
If we assume you only want the value of the cell, then your method is incorrect, as it will try to copy the entire cell to the array.
Would this work for you?
//**row.Cells.CopyTo(arrLine, 0)**
line = row.Cells[0].Value.ToString()
line &= ";" & row.Cells[1].Value.ToString()
line &= ";" & row.Cells[2].Value.ToString()
line &= ";" & row.Cells[3].Value.ToString()
line &= ";" & row.Cells[4].Value.ToString()
line &= ";" & row.Cells[5].Value.ToString()
line &= ";" & row.Cells[6].Value.ToString()
line &= ";" & row.Cells[7].Value.ToString()
line &= ";" & row.Cells[8].Value.ToString()
sw.WriteLine(line)
I generally try to avoid VisualBasic (the syntax always seems opposite to me), but from a little bit of Googling at the VB docs, I'd hazard a guess that you have a type mismatch between your string array (arrLine) and what row.Cells is trying to copy into it.
精彩评论