I have a two windows forms classes, a base class and a derived class. The base class has an event handler which handles ValueChanged on some component. I have also written a different event handler for the same event on the derived class.
When I create an instance of the derived class and fire the event, I find that both event handlers run (the base class one and then the derived class one). But I want only the handler in the derived class to run.
Is this possible and if so how do I do it?
(This is .NET 3.5) Thanks!
Edit: Here is what the code looks like (can't post the actual code):
Public Class BaseForm
Inherits System.Windows.Forms.UserControl
(Windows Form Designer Generated Code)
Private WithEvents myControl As New SomeOtherControl
Protected value As String
Private Sub my开发者_C百科Control_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myControl.ValueChanged
value = SomeLogic()
End Sub
End Class
Public Class DerivedForm
Inherits BaseForm
Private WithEvents myControl As New SomeOtherControl
Private Sub myControl_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myControl.ValueChanged
value = myControl.Value
End Sub
End Class
You can attach multiple handlers to one event so what you are seeing is by design (you have two handlers attached to the same event so they both fire).
That being said there are ways to accomplish what you are trying to do. One way is to move the code out of your base class handler into an overridable method, and then in the derived class override the method. So your base class handler only has 1 line of code,calling the new method you made. If you inherit from the class it will call your overridden method instead.
Public Class BaseForm
Private Sub myControl_ValueChanged() Handles myControl.ValueChanged
DoSomeLogic()
End Sub
Protected Overridable Sub DoSomeLogic()
'original logic here
End Sub
End Class
Public Class ChildForm
Inherits BaseForm
Protected Overrides Sub DoSomeLogic()
'other logic here
End Sub
End Class
I don't believe you can control that.
If it were me, I think I'd intercept the event in the base class, as you are doing, then define ANOTHER event from the base class and raise that event FROM the event handler in the base class.
on return, if the event was handled (presumably by your derived class), then just exit the base event handler, otherwise, proceed with the base event handling.
精彩评论