从“DBNull”类型到“String”类型的转换是无效的 vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29487702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:09:07  来源:igfitidea点击:

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

vb.net

提问by Reshma

While using the given below code showing one error. The error is: "Conversion from type 'DBNull' to type 'String' is not valid." Help me to find a proper solution. Thank you.

使用下面给出的代码显示一个错误。错误是:“ Conversion from type 'DBNull' to type 'String' is not valid.”帮助我找到合适的解决方案。谢谢你。

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()

回答by Rahul Tripathi

You should try like this:

你应该这样尝试:

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 a dirty fix like this:

或者像这样的肮脏修复:

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

回答by Reshma

You are getting this error because either sdr2("name")or sdr2("staff_id")is null. you can avoid it in two ways:

您收到此错误是因为sdr2("name")sdr2("staff_id")null。您可以通过两种方式避免它:

1.

1.

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

2. or check for null in the query

2. 或者在查询中检查 null

回答by sabikp

try like this also

也这样试试

dt.Rows(0)("name").ToString()

回答by Icepickle

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

这意味着您收到的值之一为空,并且无法转换为字符串。您可以实现一个为您进行转换的函数(并检查值是否为 dbnull 或什么都没有),如下所示:

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 could do

然后你可以做

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