簡體   English   中英

當返回空數據時,從“ DBNull”類型到“ Double”類型的轉換無效

[英]Conversion from type 'DBNull' to type 'Double' is not valid when returns empty data

我有一個包含復雜查詢的頁面。 查詢工作正常,但是每當有null或空字符串時,它將引發此錯誤。

從“ 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在頁面加載時從數據庫獲取值

在SQL中使用notull函數。

示例:選擇名稱,isnull(rating,0)

如果rating = null,則sql將返回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

使用擴展方法DataRowExtensions.Field方法(DataRow,字符串)

來自文檔:

如果指定的DataColumn的值為null,並且T為引用類型或可為null的類型,則返回類型將為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

將查詢更改為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM