Handling events from an object declared in a global module?

  • 13 years ago
    Hi!

    I have a bit of a conundrum. I have a VB.net module where I declare some global variables (and since they're in a module, they're also shared). Now, I declared them like so:






    Module modGlobals

    Public WithEvents g_Customer As New Customer()
    Public WithEvents g_Ord As New Order()

    End Module


    The events they raise are declared and raised like so (simplified):






    ' Declare eventhandler
    Public Event CustomerUpdated As eventhandler

    ' Raise the event
    Public Sub UpdateCustomer(ByVal dt As DataTable)

    RaiseEvent CustomerUpdated(Me, New System.EventArgs)

    End Sub


    Now, I attempt to write an event handler for this event on one of my forms:






    Public Sub g_Customer_CustomerUpdated(ByVal sender As Object, ByVal e As System.EventArgs) Handles g_Customer.CustomerUpdated

    'Do stuff

    End Sub


    However, the compiler kindly notifies me that "Handles clause requires a WithEvents variable defined in the containing type or one of its base types."

    Now, the g_Customer object is, as you can see, declared "WithEvents", and there is no way of declaring an instance of a module (nor would I want to). So, am I simply missing something, or can I not raise events in objects declared inside a module?

    Thanks for any help and pointers!

    Eskil









  • 13 years ago

    Maybe you can try adding the event handler dynamically at runtime.

    On the load event of your form, add the line:

    AddHandler g_Customer.CustomerUpdated, AddressOf g_Customer_CustomerUpdated

     

     

     

     

     

     

  • 13 years ago

    If you do try the above, the other thing to mention is that you can remove the 'handles' from the definition of g_customer_customerupdated

    Public Sub g_Customer_CustomerUpdated(ByVal sender As Object, ByVal e As System.EventArgs)

    'Do stuff

    End Sub



  • 13 years ago
    That worked beautifully. Thank you!

  • 13 years ago
    I'm glad it worked! Another point to make is that it's probably good practice to make a call to RemoveHandler when you're finished in your form.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“To iterate is human, to recurse divine” - L. Peter Deutsch