运营商' ='未定义类型' DBNull'和字符串" True"。 VB.net

时间:2015-04-09 07:21:09

标签: vb.net

使用下面给出的代码显示一个错误。错误是:Operator '=' is not defined for type 'DBNull' and string "True"。帮我找一个合适的解决方案。谢谢。

代码:

cmd1.CommandText = "select * FROM attendance where academic_year='" & yearTextBox.Text & "' and School_Name='" & courseDropDownList.Text & "' and Class='" & semesterDropDownList.Text & "' and batch='" & batchDropDownList.Text & "' and hour='" & DropDownList6.Text & "' and date_present='" & TextBox1.Text & "'"
sdr1 = cmd1.ExecuteReader
While sdr1.Read
  dr("student_name") = sdr1("student_name")
  dr("rollnumber") = sdr1("roll_number")
  dr("comment") = sdr1("comment")
Dim status As String = ""
  If sdr1("present") = "True" Then // ***Error popup here***
     status = "Present"
  ElseIf sdr1("Absent") = "True" Then
     status = "Absent"
  ElseIf sdr1("od") = "True" Then
     status = "OD"
  End If
  If sdr1("late") = "True" Then
     dr("status_late") = ", Latecomer"
  End If
     dr("status") = status
     dt.Rows.Add(dr)
     dr = dt.NewRow
End While
sdr1.Close()

3 个答案:

答案 0 :(得分:3)

当SQL可以为您完成工作时,为什么要通过代码费力地执行此操作:

select
    student_name,
    roll_number,
    comment,
    CASE
       WHEN present='true' THEN 'present'
       WHEN absent ='true' THEN 'absent'
       WHEN od='true' THEN 'od'
    END as status,
    CASE
       WHEN late ='true' THEN ', Latecomer'
    END as status_late
FROM attendance where academic_year=@year

并切换到使用parameterized查询来提供@year,而不是一起构建字符串。

如果您进行了上述更改,您也可以直接使用结果集切换到DataTable ExecuteReader {{1}},而不是使用{{1}}并循环并复制结果。

答案 1 :(得分:1)

这意味着数据库中检索到的值之一为NULL,因此您获得的类型为DBNull。您应首先使用NOT NULL检查检索到的值是否为.IsDBNull,然后您可以使用=对其进行比较。

答案 2 :(得分:1)

实际上,从数据库中读取数据时,必须确保读取的值是可空的或必须的。

对于Nullable值,例如,不允许将其设置为字符串。 因此,从数据库中读取数据的最佳方法是,在设置值之前需要检查IsDBNull,如下所示;

If (sdr1("present") IsNot DBNull.Value) AndAlso sdr1("present") = "True" Then 
     status = "Present"
ElseIf (sdr1("Absent") IsNot DBNull.Value) AndAlso sdr1("Absent") = "True" Then
     status = "Absent"
ElseIf (sdr1("od") IsNot DBNull.Value) AndAlso sdr1("od") = "True" Then
     status = "OD"
End If

If (sdr1("late") IsNot DBNull.Value) AndAlso sdr1("late") = "True" Then
     dr("status_late") = ", Latecomer"
End If
相关问题