user3386068
user3386068

Reputation: 43

How do I "Cancel an event"?

I have two DateTimePickers dtpDateFrom and dtpDateTo.

I already coded a conditional statement that if dtpDateTo is earlier than dtpDateFrom via their ValueChanged event, I would get an error message, but it still applies the change.

Example:

  1. dtpDateFrom = July 2
  2. dtpDateTo = July 3
  3. If I change dtpDateFrom to July 4 ~> error message + without performing the July 4 change

Upvotes: 4

Views: 5954

Answers (2)

ShawnOrr
ShawnOrr

Reputation: 1329

Try to use the Validating event for the control. In your code where your validation fails put in e.cancel = true

Private Sub dtpDateFrom_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles dtpDateFrom.Validating
    If dtpDateFrom.Value > dtpDateTo.Value Then
        Messagebox.show("From date must be less than To date")
        e.Cancel = True 'Validation failed.
    End If
End Sub

Upvotes: 3

TomTom
TomTom

Reputation: 62101

Sure it still applies. What does "VAlueChanged" mean? It means it HAS changed. The event is per documentation hrown POST FACTUM so an exception will not magically roll back time.

The key is to program in such a way that you do the validation and value rejection BEFORE changing the value.

Upvotes: 0

Related Questions