将 Byte() 转换为 Date() 时出现问题
我的 DAL 中有一个查询,结果为 1 项,即日期。它要么是日期,要么为空。但是当值为空时我会收到错误。
从“DBNull”类型到“Date”类型的转换无效。
查询
Public Function GetOrderDepositByOrderID(ByVal OrderID As Integer) As Date
myconn.Open()
Dim date As Date
Dim sql As String = "SELECT ifnull(OrderDeposit, '1900-01-01') FROM Order WHERE OrderID = ?"
Dim cmd As New OdbcCommand(sql, myconn)
cmd.Parameters.AddWithValue("OrderID", OrderID)
date= cmd.ExecuteScalar()
'connectie sluiten
myconn.Close()
Return date
End Function
这就是我调用函数的方式。
If bllCust.getOrderDepositByOrderID(OrderID) = DBNull Then
lblBoodschap.Text = ("Deposit not paid.\n")
Else
lblBoodschap.Text = ("Deposit paid.\n")
End If
如果支付了押金,表中就会有一个日期,如果没有支付,则为空。
欢迎所有帮助!
I have a query in my DAL that results 1 item, a date. It's either a date or null. But I get an error when the value is null.
Conversion from type 'DBNull' to type 'Date' is not valid.
Query
Public Function GetOrderDepositByOrderID(ByVal OrderID As Integer) As Date
myconn.Open()
Dim date As Date
Dim sql As String = "SELECT ifnull(OrderDeposit, '1900-01-01') FROM Order WHERE OrderID = ?"
Dim cmd As New OdbcCommand(sql, myconn)
cmd.Parameters.AddWithValue("OrderID", OrderID)
date= cmd.ExecuteScalar()
'connectie sluiten
myconn.Close()
Return date
End Function
This is how I call my function.
If bllCust.getOrderDepositByOrderID(OrderID) = DBNull Then
lblBoodschap.Text = ("Deposit not paid.\n")
Else
lblBoodschap.Text = ("Deposit paid.\n")
End If
If the deposit is paid there's a date in the table, if not it's left null.
All help is welcome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getOrderDepositByOrderID()
的Nullable
来检查 null,而不是C# 中的 DBNull 你的代码应该是这样的:
我不了解 VB.NET 中的
运算符
模拟或者
Nullable<DateTime>
fromgetOrderDepositByOrderID()
to check against null, not DBNullin C# your code should like this:
I don't know
operator as
analog in VB.NETor
使用操作数
IS
而不是=
Use the operand
IS
instead of=
编辑数据库字段,使空值获得默认值 1900-01-01,这是一个永远不会使用的日期。
Edited the database fields so that null values get a default value 1900-01-01, a date that will never be used.