質問

I am trying to filter my database to show all bookings for a date thats selected from a calender I have on my form. This is the code I have written...

    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

The filter i have created when debugged gives this error message...

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

Can someone show me where im making a mistake.

PS I have also tried this filter =

Me.QueryBookingInfoBindingSource.Filter = "BookingDate >= #" & dateFrom.ToString("dd/MM/yyyy hh:mm:ss") & "# AND BookingDate <= #" & dateTo.ToString("dd/MM/yyyy hh:mm:ss") & "#"
役に立ちましたか?

解決

Have you tried formatting your dates?

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)

EDIT:

This IMHO is cleaner and easier to read:

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

This will also be able to receive dates with time values without crashing, which your former code wouldn't. ;) That being said, since selDate is declared outside the method, you probably don't want a parameterized method to begin with.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top