Link to home
Create AccountLog in
Avatar of dreinmann
dreinmannFlag for United States of America

asked on

Temporarily Disable EventHandler?

I have a DateTimePicker that I want to do something on it's ValueChanged event, but then I want to change the Value back to 'Yesterday's Date' without firing another event.
I've tried RemoveHandler/AddHandler, but it doesn't seem to work.

  Private Sub dtpRequest_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtpRequest.ValueChanged
        Dim request As String
        request = CStr(dtpRequest.Value.Date)
        If lbxRequestedDays.Items.Contains(request) = True Then
            MsgBox("This day has already been selected.", vbOKOnly, "Attention")
        Else
            lbxRequestedDays.Items.Add(request.ToString)
        End If
        lblDaysOff.Text = lbxRequestedDays.Items.Count.ToString & " days"
        lblDaysOff.Refresh()
    End Sub
ASKER CERTIFIED SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Actually there are a couple functions that provide this functionality.  The RemoveHandler and AddHandler functions removes and adds the association respectively.

Try this code out.  If you click button one, you'll get a message box.  If you click button two then button one, nothing happens.  You can also add AddHandler to reassociate the event.

Public Class Form1
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        RemoveHandler Button1.Click, AddressOf Button1_Click
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox("one")
    End Sub
End Class

Let me know if you have any questions.

~b
Sorry - you've already tried that...guess I should read the whole question :)
Avatar of dreinmann

ASKER

Yes, this code will run through twice.  If I take out the part with the RemoveHandler and value changing to yesterday, it only runs once:
Private Sub dtpRequest_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtpRequest.ValueChanged
        Dim request As String
        request = CStr(dtpRequest.Value.Date)
        If lbxRequestedDays.Items.Contains(request) = True Then
            MsgBox("This day has already been selected.", vbOKOnly, "Attention")
        Else
            lbxRequestedDays.Items.Add(request.ToString)
        End If
        RemoveHandler dtpRequest.ValueChanged, AddressOf dtpRequest_ValueChanged
        dtpRequest.Value = Now().AddDays(-1).Date
        AddHandler dtpRequest.ValueChanged, AddressOf dtpRequest_ValueChanged

        lblDaysOff.Text = lbxRequestedDays.Items.Count.ToString & " days"
        lblDaysOff.Refresh()
    End Sub