代码运行了两次

时间:2012-04-24 17:55:33

标签: vb.net

我已经有了开始日期来验证是否在结束日期和显示消息之后,但是当我输入以下代码.focus它似乎运行代码两次 我尝试了一切 把手离开了 试过它没有用 我也把它放到一个新的线程,没有工作 并且还成功能,没有工作 我很高兴见到这一个

这是代码

Function DateCompare(ByVal Start As Date, ByVal Finish As Date, ByVal WhichDate As String)
  If WhichDate = "DateIn" Then
    If DateTime.Compare(Start, Finish) > 0 Then
      MsgBox("Dates Are Invalid : Date In Cannot be after Date Out, Please Amend", vbExclamation, "Dates Are Incorrect")
      Return False
      Exit Function
    Else
      Return True
    End If
  Else
    If DateTime.Compare(Finish, Start) < 0 Then
      MsgBox("Dates Are Invalid : Date Out Cannot be before Date In, Please Amend", vbExclamation, "Dates Are Incorrect")
      Return False
      Exit Function
    Else
      Return True
    End If
  End If
End Function

Private Sub dtpDateTimeIn_leave(ByVal sender As Object, ByVal e As EventArgs) Handles dtpDateTimeIn.Leave
  Dim result As Boolean
  result = DateCompare(dtpDateTimeIn.Value, dtpDateTimeOut.Value, "DateIn")
  If result = False Then
    dtpDateTimeIn.Focus()
  End If
End Sub

Private Sub dtpDateTimeOut_leave(ByVal sender As Object, ByVal e As EventArgs) Handles dtpDateTimeOut.Leave
  Dim result As Boolean
  result = DateCompare(dtpDateTimeIn.Value, dtpDateTimeOut.Value, "DateOut")
  If result = False Then
    dtpDateTimeOut.Focus()
  End If
End Sub

1 个答案:

答案 0 :(得分:0)

请尝试使用Validating事件。他们是为此而做的:

Private Sub dtpDateTimeIn_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles dtpDateTimeIn.Validating
  e.Cancel = Not DateCompare(dtpDateTimeIn.Value, dtpDateTimeOut.Value, "DateIne")
End Sub

Private Sub dtpDateTimeOut_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles dtpDateTimeOut.Validating
  e.Cancel = Not DateCompare(dtpDateTimeIn.Value, dtpDateTimeOut.Value, "DateOut")
End Sub