Thomas Dutoit
Thomas Dutoit

Reputation: 139

How to compare and SQL date in VB.net

I have a SQL Server database and what I want to do is compare a start date (date) and an end date (date) that I stored in my database on a row like this:

Both of these dates must be checked with the current date inside a sub in vb.net and I did this:

If RecieverData.HasRows Then
    While RecieverData.Read
        Label1Recieverinfo.Text = "Klant: " & RecieverData("Ontvanger").ToString
        Label2Recieverinfo.Text = "ID: " & RecieverData("OntvangerID").ToString
        Label3Recieverinfo.Text = "Event: " & RecieverData("event").ToString
        Label4Recieverinfo.Text = "Startdatum: " & RecieverData("Startdate").ToString
        Label5Recieverinfo.Text = "Einddatum: " & RecieverData("Enddate").ToString
    End While

    Dim StartDate As New Date
    Dim EndDate As New Date

    StartDate = RecieverData("StartDate")
    EndDate = RecieverData("EndDate")

    If StartDate <= Date.Now Then
        MessageBox.Show("startdate ok")
    ElseIf EndDate >= Date.Now Then
        MessageBox.Show("Enddate ok")
    Else
        MessageBox.Show("Use me")
    End If

Else
    MessageBox.Show("Deze Ontvanger ID bestaat niet.", "Fout", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If

But (you already knew this) it doesn't work.

Can someone help me out here?

Thanks

Edit:

Label results:

enter image description here

Error that I get:

enter image description here

Upvotes: 1

Views: 1264

Answers (1)

Mark
Mark

Reputation: 8160

Your while loop is reading past the end of the data. If you only expect one row, you should just read once:

If RecieverData.HasRows Then

    ' Read the first row
    RecieverData.Read()

    Label1Recieverinfo.Text = "Klant: " & RecieverData("Ontvanger").ToString
    Label2Recieverinfo.Text = "ID: " & RecieverData("OntvangerID").ToString
    Label3Recieverinfo.Text = "Event: " & RecieverData("event").ToString
    Label4Recieverinfo.Text = "Startdatum: " & RecieverData("Startdate").ToString
    Label5Recieverinfo.Text = "Einddatum: " & RecieverData("Enddate").ToString

    Dim StartDate As New Date
    Dim EndDate As New Date

    StartDate = RecieverData("StartDate")
    EndDate = RecieverData("EndDate")

    If StartDate <= Date.Now Then
        MessageBox.Show("startdate ok")
    ElseIf EndDate >= Date.Now Then
        MessageBox.Show("Enddate ok")
    Else
        MessageBox.Show("Use me")
    End If

Else
    MessageBox.Show("Deze Ontvanger ID bestaat niet.", "Fout", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If

Upvotes: 3

Related Questions