如何在Visual Basic 2012中使用BindingSource.Filter作为日期?

时间:2014-02-18 16:50:18

标签: vb.net visual-studio-2012 bindingsource

我正在尝试过滤我的数据库,以显示从我在表单上的日历中选择的日期的所有预订。这是我写的代码......

    Public selDate As DateTime
Dim response As Integer

Public Sub FilterBooking(selDate)
    '// Here I will create a filter to for boookings on selected date from calender

    Dim dateFrom As DateTime
    Dim dateTo As DateTime

    dateFrom = selDate & " 00:00:01"
    dateTo = selDate & " 23:59:59"
    MsgBox(dateFrom)
    MsgBox(dateTo)

    Me.QueryBookingInfoBindingSource.Filter = "BookingDate >= #" & dateFrom & "# AND BookingDate <= #" & dateTo & "#"
End Sub

Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'GarageDataSet.queryBookingInfo' table. You can move, or remove it, as needed.
    Me.QueryBookingInfoTableAdapter.Fill(Me.GarageDataSet.queryBookingInfo)
    'set currently selected date in the main calender to selDate variable
    selDate = mainCalender.SelectionStart.Date
    'run the following sub
    FilterBooking(selDate)
End Sub

我在调试时创建的过滤器提供了此错误消息...

  

mscorlib.dll中发生未处理的“System.FormatException”类型异常

     

其他信息:字符串未被识别为有效的DateTime。

有人可以告诉我哪里犯了错误。

PS我也试过这个过滤器=

Me.QueryBookingInfoBindingSource.Filter = "BookingDate >= #" & dateFrom.ToString("dd/MM/yyyy hh:mm:ss") & "# AND BookingDate <= #" & dateTo.ToString("dd/MM/yyyy hh:mm:ss") & "#"

1 个答案:

答案 0 :(得分:2)

您是否尝试过格式化日期?

Me.QueryBookingInfoBindingSource.Filter = "BookingDate >= " & String.Format("#{0:yyyy/MM/dd HH:mm:ss}#", dateFrom) & " AND BookingDate <= " & String.Format("#{0:yyyy/MM/dd HH:mm:ss}#", dateTo)

修改

这个恕我直言,更清晰,更容易阅读:

Public Sub FilterBooking(selDate)
    Dim dateFrom As DateTime = selDate.Date
    Dim dateTo As DateTime = dateFrom.AddDays(1).Subtract(New TimeSpan(1))

    Dim filterBuilder As New StringBuilder()
    Dim filterFormat As String = "BookingDate {0} #{1:yyyy/MM/dd HH:mm:ss}#"

    With filterBuilder
        .AppendFormat(filterFormat, ">=", dateFrom)
        .Append(" AND ")
        .AppendFormat(filterFormat, "<=", dateTo)
    End With

    Me.QueryBookingInfoBindingSource.Filter = filterBuilder.ToString()
End Sub

这也可以接收带有时间值的日期而不会崩溃,而以前的代码则不会。 ;)话虽如此,因为selDate是在方法之外声明的,所以你可能不希望以参数化方法开头。