我一直在这个项目中得到一些帮助,我很想解决这个问题,所以我可以继续这个项目的其余部分。
我有一个gridview设置为保存到文件,并且可以选择导入到excel。 我一直收到错误:
无效的投射例外未处理。 源数组中至少有一个元素无法转换为目标数组类型。
谁能告诉我外行人很容易理解这个错误在说什么?
这是我尝试使用的代码:
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
我在调试中显示了它所显示的行,我真的没有看到关于LOL的所有大惊小怪
答案 0 :(得分:2)
如果我们假设您只想要单元格的值,那么您的方法是不正确的,因为它会尝试将整个单元格复制到数组中。
这对你有用吗?
//**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)
答案 1 :(得分:0)
我一般都试图避免使用VisualBasic(语法总是与我相反),但是从VB文档中的一点点Google搜索,我猜测你的字符串数组(arrLine)之间的类型不匹配什么row.Cells试图复制到它。