Raj Jayaswal
Raj Jayaswal

Reputation: 478

Cancelling the button click event in its derived class

Very recently, I was working on a custom button, in which I had to capture the event of the button, and depending on the certain conditions, either I'll block the event or pass it on the form containing my custom button.

Here is prototype of the code I was working on:

Public Class MyCustomButton
    Inherits Windows.Forms.Button

    Private Sub Me_Clicked(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Click
        Dim i As Integer = MsgBox("Are you sure you want to perform the operation?", MsgBoxStyle.YesNoCancel, "MyApp")
        If Not i = 6 Then
            'Cancel the event
        Else
            'Continue with the event
        End If
    End Sub
End Class

Now, I do not have any idea how to block the event and not allow it to pass if the users opts for "No" in the given example. Any suggestions?

Upvotes: 1

Views: 3606

Answers (1)

LarsTech
LarsTech

Reputation: 81620

You need to override the OnClick event:

Public Class MyCustomButton
  Inherits Button

  Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
    Dim i As Integer = MsgBox("Are you sure you want to perform the operation?", MsgBoxStyle.YesNoCancel, "MyApp")
    If Not i = 6 Then
      'Cancel the event
    Else
      MyBase.OnClick(e)
    End If
  End Sub

End Class

Upvotes: 2

Related Questions