How do I set a nullable DateTime to null in VB.NET?

我只是一个虾纸丫 提交于 2019-11-27 03:51:38

问题


I am trying to set up a date range filter on my UI, with checkboxes to say whether a DateTimePicker's value should be used, e.g.

Dim fromDate As DateTime? = If(fromDatePicker.Checked, fromDatePicker.Value, Nothing)

Yet setting fromDate to Nothing doesn't result in it being set to Nothing but to '12:00:00 AM', and the following If statement incorrectly executes the filter because startDate is not Nothing.

If (Not startDate Is Nothing) Then
    list = list.Where(Function(i) i.InvDate.Value >= startDate.Value)
End If

How do I really ensure startDate gets a value of Nothing?


回答1:


The issue is that it's examining the right-hand side of this assignment first, and deciding that it is of type DateTime (no ?). Then performing the assignment.

This will work:

Dim fromDate As DateTime? = If(fromDatePicker.Checked, _
                               fromDatePicker.Value, _
                               CType(Nothing, DateTime?))

Because it forces the right-hand side's type to be DateTime?.

As I said in my comment, Nothing can be more akin to C#'s default(T) rather than null:

Nothing represents the default value of a data type. The default value depends on whether the variable is of a value type or of a reference type.




回答2:


With VB.NET and EF 6.X to save null is:

Dim nullableData As New Nullable(Of Date)




回答3:


In addition to @Damien_The_Unbeliever's fine answer, using New DateTime? also works:

Dim fromDate As DateTime? = If(fromDatePicker.Checked, _
                               fromDatePicker.Value, _
                               New DateTime?)

You might find that it looks a bit counter intuitive, why perhaps the CType(Nothing, DateTime?) is preferable.




回答4:


Use New Date as a magic number:

Dim fromDate As New Date
If fromDatePicker.Checked Then
  fromDate = fromDatePicker.Value
End If
If fromDate <> New Date Then
  list = list.Where(Function(i) i.InvDate.Value >= fromDate.Value)
End If



回答5:


        squery = "insert into tblTest values('" & Me.txtCode.Text & "', @Date)"
        Dim cmd = New SqlCommand(squery, con)

        cmd.Parameters.Add("@Date", SqlDbType.DateTime)
        If txtRequireDate.Text = "" Then
            cmd.Parameters("@Date").Value = DBNull.Value
        Else
            cmd.Parameters("@Date").Value = txtRequireDate.Text
        End If


来源:https://stackoverflow.com/questions/12595775/how-do-i-set-a-nullable-datetime-to-null-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!