如何解决这个问题:从类型DBNull到类型字符串的转换无效

时间:2016-08-12 01:11:45

标签: vb.net crystal-reports

  1. 我认为这是因为我认为在创建报告后关闭水晶报告时会出现错误。

    Private Sub Populate(id As Integer, perdate As Date, controlnum As String, establishmentname As String, fname As String, mname As String, lname As String, address As String, pertype As String, ornum As String, amntpd As String, datepd As Date)
    
    Dim row As String() = New String() {id, perdate, controlnum, establishmentname, fname, mname, lname, address, pertype, ornum, amntpd, datepd}
    
    DataGridView1.Rows.Add(row)
    
    End Sub
    
  2. 这是从我的数据库(MySql数据库)到datagrid视图检索数据的代码

        Private Sub retrieve()
        DataGridView1.Rows.Clear()
        sql = "SELECT * FROM tblfsesmis"
    
    
        Try
            Using con
                con.Open()
                cmd = New MySqlCommand(sql, con)
                adapter = New MySqlDataAdapter(cmd)
    
                adapter.Fill(dt)
    
                For Each row In dt.Rows
                    'It's in your Populate function that you want to check the DBNull values
                    Populate(row(0), row(1), row(2), row(3), row(4), row(5), row(6), row(7), row(8), row(9), row(10), row(11))
                Next
    
                dt.Rows.Clear()
                DataGridView1.Refresh()
            End Using 'con Object will be disposed automatically
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    
    End Sub
    

    你能帮我解决这个问题吗?请 !谢谢

3 个答案:

答案 0 :(得分:0)

如果您的应用程序不支持某个字段的空值,请修改您的查询,以便无法显示空值。

所以代替:.babelrc

使用SELECT * FROM tblfsesmis

IsNull将使用您选择的默认值替换空值。

或者,您可以使用类似

的代码修复此问题 每个字段上的

SELECT Id, PerDate, IsNull(ControlNum, '') .... FROM tblfsesmis可能为空。

然而,正如评论中指出的那样,您似乎无需将这些值转换为字符串。所以只需将数据表直接分配给数据源。

答案 1 :(得分:0)

    Private Sub retrieve()
sql = "SELECT * FROM tblfsesmis"


Try
    Using con
        con.Open()
        cmd = New MySqlCommand(sql, con)
        adapter = New MySqlDataAdapter(cmd)

        adapter.Fill(dt)

        DataGridView1.DataSource = dt
    End Using 'con Object will be disposed automatically
Catch ex As Exception
    MsgBox(ex.Message)
End Try

End Sub

答案 2 :(得分:0)

使用DataRow.Field(Of T)扩展程序。
使用DataRow.Field(Of String)(columnIndex)如果值为DbNull,则会返回Nothing/null

Populate(row.Field(Of Integer)(0), row.Field(Of String)(1))

如果Integer类型的列也可以是NULL,则使用Nullable方法<{1}}

GetValueOrDefault

但正如@ F0r3v3r-A-N00b建议的那样 - 您可以使用Populate(row.Field(Of Integer?)(0).GetValueOrDefault(), row.Field(Of String)(1)) 作为DataTable的数据源。

DataGridView

这样Private Sub retrieve() Dim sql As String = "SELECT * FROM tblfsesmis" Try Using con As New MySqlConnection(yourConnectionString) con.Open() Using cmd As New MySqlCommand(sql, con) Dim adapter As New MySqlDataAdapter(cmd) Dim dt As New DataTable() adapter.Fill(dt) DataGridView1.DataSource = dt End Using End Using Catch ex As Exception MsgBox(ex.Message) End Try End Sub 将自动更新。只需检查DataGridView(默认为真)