0

I'm creating a program that is meant to run in the background, but with the opportunity to select a time where the program is supposed to appear on the screen again. I'm not sure how to do this, but i assume it's possible with a simple 'if' within my timer?

This is the code from the top of my head (wich obviously isn't working)

    Dim time As DateTime = DateTime.Now
    Dim format As String = "HH:mm"
    Label10.Text = (time.ToString(format))
    If DateAndTime.Now() = Textbox1.Text Then
        Me.Show()
    End If

Thanks :)

Freshman
  • 293
  • 3
  • 8
  • 19

3 Answers3

2

A couple of obvious errors. First, you are comparing a DateTime to a String in the If statement and letting the runtime handle the conversion. You should do the conversion explicitly. In fact, you should configure the application so that Option Strict and Option Explicit are enabled. This greatly reduces the number of problems that can show up. See this question

Second, Comparing a DateTime value to DateTime.Now must best done with an inequality since its resolution is down to fractions of a second. It would be an absolute fluke if you hit that If statement when the times are equal.

    Dim time As DateTime = DateTime.Now
    Dim format As String = "HH:mm"
    Label10.Text = (time.ToString(format))
    Dim ShowTime As DateTime
    If DateTime.TryParse(Textbox1.Text, ShowTime) Then
        If DateTime.Now() > ShowTime Then
            Me.Show()
        End If
    End If

Also, is there a specific reason for mixing DateTime usage and DateAndTime usage? DateAndTime is to simplify translating old VB 6 code into VB.NET. You should get in the practice of just using DateTime for new code.

Community
  • 1
  • 1
Gridly
  • 938
  • 11
  • 13
0

Ah, just a minor problem, I'll add my solution incase someone got the same problem with logical thinking :)

Dim time As DateTime = DateTime.Now
Dim format As String = "HH:mm"
Dim stopp As DateTime = stopTime.Text
Label10.Text = (time.ToString(format))
If Label10.Text = stopp Then
    Me.Show()
Else
    stopp = stopTime.Text
End If
Freshman
  • 293
  • 3
  • 8
  • 19
0

I think you code can be greatly simplified by just using the overloaded ToString of DateTime.Now method and comparing this against the textbox.

This assumes the time entered in the TextBox is in HH:mm format:

    If DateTime.Now.ToString("HH:mm") = TextBox1.Text Then
        Timer1.Enabled = False
        MessageBox.Show("Stop")
    End If

But you should be using a DateTimePicker control if you want the user to enter a date or a time. This makes the comparison less ambiguous as you do not have to convert a date to a spcific format of string:

If (DateTime.Now.Hour = DateTimePicker1.Value.Hour) AndAlso 
   (DateTime.Now.Minute = DateTimePicker1.Value.Minute) Then
      Timer1.Enabled = False
      MessageBox.Show("Stop")
End If
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143