【问题标题】:"value of type datagridviewcell can not be converted to string" vb.net“datagridviewcell 类型的值不能转换为字符串”vb.net
【发布时间】:2017-01-11 04:27:51
【问题描述】:

我正在尝试从 DataGridView 中获取数据并将该数据保存到 txt 文件中,以便稍后将其加载到网格中。现在,它将保存文件,但由于错误而不会写入文件

“datagridviewcell 类型的值不能转换为字符串”或

“在 mscorlib.dll 中发生了类型为‘System.FormatException’的未处理异常 附加信息:输入字符串的格式不正确。"

我不知道该怎么做,也找不到任何解决方案。

Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
    'SGD is my save file dialog box
    SGD.ShowDialog()
    Using writer As New StreamWriter(SGD.FileName)
        For Each row As DataGridViewRow In QAfield.Rows
            writer.WriteLine(row.Cells.Item("AgentColumn").ToString, row.Cells.Item("ScoreColumn"), row.Cells.Item("PassColumn"), row.Cells.Item("FailColumn"))

        Next
    End Using
End Sub

【问题讨论】:

标签: string vb.net datagridview


【解决方案1】:

错误是因为您没有访问valueDataGridViewCell 而是单元格本身...

这个返回是DataGridViewCell

 row.Cells.Item("AgentColumn")

当您添加 ToString 时,您正在尝试获取此对象并将其转换为字符串,这将不起作用并且您看到的确切错误。

  row.Cells.Item("AgentColumn").ToString

您需要访问value 本身...

 row.Cells.Item("AgentColumn").Value.ToString()

另外,如果Value 为NULL,则在添加ToString 时将引发异常,因为您不能将NULL 强制转换为空字符串。在将其转换为字符串之前,我会检查此 value...

 If row.Cells.Item("AgentColumn").Value IsNot DBNull.Value Then ....

【讨论】:

  • 非常感谢!
  • 欢迎,很高兴能帮到你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
相关资源
最近更新 更多