2012-08-06 141 views
4

我有以下ASP.NET(VB)代码:ASP.NET VB - 从型 '的DBNull' 转换到类型 '字符串' 无效

strLocation = CStr(q1("LocationName")) + " " + CStr(q1("LocationAddress")) + " " + CStr(q1("LocationCity")) 

作为LocationCity为空:

我从类型'DBNull'转换为类型'String'无效。

有没有办法解决这个问题。

如果这只是LocationCity我可能会做这样的事情:

If IsDBNull(q1("LocationCity")) Then 
     strLocation = "" 
    Else 
     strLocation = CStr(q1("LocationCity")) 
    End If 

我也试过:

strLocation = If(CStr(q1("LocationName")), "") + " " + If(CStr(q1("LocationAddress")), "") + " " + If(CStr(q1("LocationCity")), "") 

,但得到了同样的结果

在C#中我通常会使用? ?但不知道在ASP.NET VB

+0

发生了什么?你是否在你的if语句中使用另一个语句并抛出了一个execption?调试器告诉你什么?如果你检查是否真的是dbnull?你使用哪个数据库和提供者? – 2012-08-06 15:16:43

回答

2

最好的方法,你可以使用If(IsDBNull(q1("propertyName")), "", CStr(q1("propertyName")))

或者你可以执行的代码块,你表现为一个方法,并呼吁每个属性,方法。海事组织,它将使你的代码行比使用3个IIF语句

Function StringValue(q1 as Q1Type) as String 
    If IsDBNull(q1("LocationCity")) Then 
     Return "" 
    Else 
     Return CStr(q1("LocationCity")) 
    End If 
End Function 

strLocation = StringValue(q1("LocationName")) + " " + StringValue(q1("LocationAddress")) + " " + StringValue(q1("LocationCity")) 
+0

'IIF'执行“true”和“false”参数,因此你答案的那部分不起作用 – freefaller 2012-08-06 15:25:22

相关问题