Conversion from type "DBNull" to type "String" is not valid vb.net

When using the code below, one error is displayed. Error: " Conversion from type 'DBNull' to type 'String' is not valid." Help me find the right solution. Thank.

the code:

cmd2.CommandText = "SELECT [first_name]+' ' +[middle_name]+' ' + [last_name] AS NAME, [staff_id] FROM [staff_profile]"
sdr2 = cmd2.ExecuteReader
While sdr2.Read
drop1l.Items.Add(New ListItem(sdr2("name"), sdr2("staff_id"))) // error popup here
End While
sdr2.Close()
+4
source share
3 answers

You should try:

If Not IsDBNull(dt.Rows(0)("name")) Then
    sdr2.Value = dt.Rows(0)("name")
End If
If Not IsDBNull(dt.Rows(1)("staff_id")) Then
    sdr2.Value = dt.Rows(1)("staff_id")
End If

or dirty fix:

drop1l.Items.Add(New ListItem(sdr2("name").ToString(), sdr2("staff_id").ToString()))
+8
source

You get this error because either sdr2("name"), or sdr2("staff_id")- null. You can avoid this in two ways:

1.

drop1l.Items.Add(New ListItem(sdr2("name").Tostring(), sdr2("staff_id").Tostring())) 

2. or check the null value in the request

+2
source

This means that one of the values ​​you received is null and it cannot be sent to a string. You can implement a function that does the casting for you (and checks if the value is dbnull or nothing), something in the line:

Function GetStringValue(value as Object) as String
    if value is Nothing or IsDBNull(value)then
        Return String.Empty
    End If
    Return DirectCast(value, GetType(String))
End Function

and then you can do

drop1l.Items.Add(new ListItem(GetStringValue(sdr2("name")), GetStringValue(sdr2("staff_id")))
+1
source

All Articles