我有一个包含复杂查询的页面。查询正常工作但只要有空字符串或空字符串就会抛出此错误。
从“DBNull”类型转换为“Double”类型无效。
这是我的代码
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData("SELECT (`behaviour`+`treatment`+`charges`+`information`+`hygine`+`admission`)/6 AverageRating, COUNT(ID) RatingCount from ratings WHERE hospitalID Like '%" + var2 + "%';")
avg.Text = FormatNumber(CDbl(dt.Rows(0)("AverageRating")), 1)
totalVotes.Text = String.Format(dt.Rows(0)("RatingCount"))
End If
avg.text从页面加载时的db获取值
答案 0 :(得分:0)
在SQL中使用isnull函数。
示例:选择名称,isnull(评级,0)
如果rating = null,则sql将返回0
答案 1 :(得分:0)
Double.TryParse(text, value)
最擅长测试
If Not Me.IsPostBack Then
Dim testDouble as Double
Dim dt As DataTable = Me.GetData("SELECT (`behaviour`+`treatment`+`charges`+`information`+`hygine`+`admission`)/6 AverageRating, COUNT(ID) RatingCount from ratings WHERE hospitalID Like '%" + var2 + "%';")
If Double.TryParse((dt.Rows(0)("AverageRating")), testDouble) Then
' text is convertible to Double, and testDouble contains the Double value now'
avg.Text = FormatNumber(testDouble, 1)
Else
' Cannot convert text to Double'
End If
totalVotes.Text = String.Format(dt.Rows(0)("RatingCount"))
End If
答案 2 :(得分:0)
使用扩展方法DataRowExtensions.Field Method (DataRow, String)
来自文档:
如果指定的DataColumn的值为null且T是引用 type或nullable类型,返回类型将为null。
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData("SELECT ....")
Dim avgValue As Double? = dt.Rows(0).Field(Of Double?)("AverageRating")
If avgValue.HasValue = True Then
avg.Text = avgValue.Value.ToString()
Else
avg.Text = "no value"
End If
End If
答案 3 :(得分:0)
将您的查询更改为
SELECT (isnull(`behaviour`,0)+isnull(`treatment`,0)+isnull(`charges`,0)+isnull(`information`,0)+isnull(`hygine`,0)+isnull(`admission`,0))/6 AverageRating, COUNT(ID) RatingCount from ratings