RaiseEvent in inherited classes

Sorry if this is a FAQ: I've read the error notice in help (VS 2005 Visual Basic Express Edition beta 2) saying that I have to "move" the declaration of an event into the class I want to use it in. Doing that means that the

  Dim WithEvents myvar As ParentClass

in the MainForm module causes an error because the class doesn't have any events.

My problem is that I want to Dim the parent (mustinherit) class because I want to be able to choose at run time which of two inherited classes I want to use; and I want to use a common routine in the MainForm to display changes in the class.

I've tried declaring this in the child classes:

  Public Shadows Event ThingMoved(a as integer etc)

but that prevents any events being raised in the MainForm. Presumably there is a legal way round this... Help

Thanks in advance


Tim Ferguson



Answer this question

RaiseEvent in inherited classes

  • Terry Heath

       Protected Overridable Sub OnMyEvent( _
           ByVal
    e As EventArgs)
         RaiseEvent MyEvent(Me, e)
       End Sub

    Wow: that was fast, and just what I needed. Many thanks


    Tim




  • rreineri

    You can use a pattern like this:



    Public
    MustInherit Class ParentClass
       Public Event MyEvent(ByVal sender As Object, ByVal e As EventArgs)

       Protected
    Overridable Sub OnMyEvent(ByVal e As EventArgs)
          RaiseEvent MyEvent(Me, e)
       End Sub
    End
    Class

    Public Class ChildClass1
       Inherits ParentClass
       
       Public
    Sub SubThatWantsToFireEvent()
          OnMyEvent(EventArgs.Empty)
       End Sub
    End
    Class

     



    Or you could use an interface instead of an abstract (must inherit) base class



    Public
    Interface IEventSource
       Event MyEvent(ByVal sender As Object, ByVal e As EventArgs)
    End Interface

    Public Class ChildClass2
       Implements IEventSource

       Public
    Event MyEvent(ByVal sender As Object, ByVal e As System.EventArgs) Implements IEventSource.MyEvent
    End Class

     



    Best regards,
    Johan Stenberg



  • RaiseEvent in inherited classes