我有一个sub,它只是将访问数据库中的值添加到文本框中。但是,db中的某些字段包含空值或为空,这会导致vb抛出错误,“无法从DBNull转换为字符串”。
如何根据我发布的代码修复此问题,或者是否有人可以发布此类事件的教程,因为我是一个努力理解这一点的新用户。非常感谢
Sub add()
While dr.Read()
txtname.Text = dr(0).ToString()
txtfathername.Text = dr(1).ToString()
txtaddress.Text = dr(2).ToString()
txtemail.Text = dr(3).ToString()
End While
End Sub
更新
Sub filllistview()
Try
'creatconn()
cn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("Select * from Postings", cn)
dr = cmd.ExecuteReader()
While dr.Read()
ListView1.Items.Add(dr(0).ToString())
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr(1))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr(2))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr(3))
End While
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
Finally
dr.Close()
cn.Close()
End Try
End Sub
Sub showcontectsinlistview()
Try
'creatconn()
cn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("select * from Postings where [Code]='" & ListView1.Text & "'", cn)
dr = cmd.ExecuteReader()
add()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
Finally
dr.Close()
cn.Close()
End Try
End Sub
答案 0 :(得分:1)
我认为您应该检查值是否为NULL
Sub add()
While dr.Read()
If dr(0) Then txtname.Text = dr(0).ToString()
If dr(1) Then txtfathername.Text = dr(1).ToString()
If dr(2) Then txtaddress.Text = dr(2).ToString()
If dr(3) Then txtemail.Text = dr(3).ToString()
End While
End Sub
可能有更好的方法......
答案 1 :(得分:1)
检测来自该行的数据是否先为空,然后将其替换为其他值,并将其转换为字符串,然后将其传递到文本框
使用无效功能:
dim x as string
if dr(0).value = nothing then
x = "Null data"
else
x = dr(0).value
end if
当您从数据库中读取数据时,似乎存在问题。你可以尝试将查询更改为不输出空值吗?
类似
SELECT Field
FROM Table
WHERE Not(Field) is null;
答案 2 :(得分:1)
您需要首先检查值IsDBNull
是否如此
Dim value As String = If(dr.IsDBNull(dr(0)), "", dr(0).ToString())
然后使用value
你可以将这个逻辑放入一个方法并从那里返回。
或在您的方法中:
Sub add()
While dr.Read()
If dr(0) Then txtname.Text = If(dr.IsDBNull(dr(0)), "", dr(0).ToString())
If dr(1) Then txtfathername.Text = If(dr.IsDBNull(dr(1)), "", dr(1).ToString())
If dr(2) Then txtaddress.Text = If(dr.IsDBNull(dr(2)), "", dr(2).ToString())
If dr(3) Then txtemail.Text = If(dr.IsDBNull(dr(3)), "", dr(3).ToString())
End While
End Sub
还要检查其他SO答案:SQL Data Reader - handling Null column values
.Add(dr(0).ToString())
变为:
.Add(If(dr.IsDBNull(dr(0)), "", dr(0).ToString()))