数据库问题。数据是空的。无法在Null值上调用此方法或属性。
Dim query = "Select DISTINCT SUM(bi.[QTY]) as CountQTY From mytable..."
Dim reader1 As SqlDataReader = cmd3.ExecuteReader()
While reader1.Read()
If IsDBNull(reader1) Then
CartCountL.Text = 0
Else
CartCountL.Text = reader1.GetInt32(0)
End If
End While
答案 0 :(得分:1)
因为即使它是Row
,您总是至少有一个NULL
,您应该检查该值。你可以这样做:
Dim query As SqlCommand = "Select DISTINCT SUM(bi.[QTY]) as CountQTY From mytable..."
Dim reader1 As SqlDataReader = query.ExecuteReader()
CartCountL.Text = "0"
While reader1.Read()
If IsDBNull(reader1.GetInt32(0)) = False Then
CartCountL.Text = reader1.GetInt32(0).ToString()
End If
End While
您还可以在数据库级别处理NULL
,如下所示:
Dim query As SqlCommand = "Select DISTINCT SUM(COALESCE(bi.[QTY], 0)) as CountQTY From mytable..."
然后所需的代码很简单:
While reader1.Read()
CartCountL.Text = reader1.GetInt32(0).ToString()
End While
答案 1 :(得分:0)
您应该将IsDBNull
更改为IsNothing
,如注释中所述,SqlDataReader是一个对象。它永远不会是DBNull
,但可以是null
/ Nothing
。
Dim query As String = "Select DISTINCT SUM(bi.[QTY]) as CountQTY
From mytable..."
Using sqlConn As New SqlConnection(ConnectionString)
Dim cmd3 As New SqlCommand(query, sqlConn)
sqlConn.Open()
Dim reader1 As SqlDataReader = cmd3.ExecuteReader()
If reader1.HasRows Then
While reader1.Read()
CartCountL.Text = reader1.GetInt32(0)
End While
Else
CartCountL.Text = 0
End If
reader.Close()
End Using
答案 2 :(得分:0)
只是想分享另一种做法的方法。如果你想检查多列
,我认为这很好 Dim reader1 As SqlDataReader = cmd3.ExecuteReader()
While reader1.Read()
CartCountL.Text = IIf(IsDBNull(reader1("CountQTY")), "0", reader1("CountQTY"))
End While