Handle Events of Object defined in another class/file

.net, events, vb.net

Solution

The key is the part of the message: `requires a WithEvents variable defined in the containing type`. Your `foo` is not defined in the containing type (your Form in this case). There are two ways to do this.

Use the module/global declaration to provide scope foro the Foo object:

Public mainFoo As FooBar

It really only needs to be `Friend`, but since there is nothing to subscribe to events here, it doesnt need to be `WithEvents`. Forms/objects which just need access to `Foo` (not the events) can reference this `mainFoo` object.

Next, any form or class which wishes to subscribe to Foo events, does need a local `WithEvents` variable set to the global object:

Private WithEvents myFoo As FooBar    ' variable declaration

myFoo = mainFoo       ' set myFoo to reference the real object

The advantage to this method is that in the form code, you should be able to select myFoo from the menu on the left, then the FooEvent from the menu on the right for VB/VS to insert the correct event handler as it does with control events:

Private Sub myFoo_FooChanged(sender As Object, newFoo As String) _
       Handles myFoo.FooChanged

This other method is slightly simpler, just use AddHandler to manually hook up that main variable:

AddHandler mainFoo.FooChanged, AddressOf sub_FooChanged

It prevents having to create a local `WithEvents` variable, but it also prevents VS from creating the Event procedures for you.

Problem

I have a VB.NET program where I have multiple forms and some variables that I want to access on all the forms, so I've created a module file that contains some public variables. What I'm finding is that though these variables have been declared `WithEvents`, their events cannot be handled on forms without first copying to a local variable. Pseudo-Code for what's going on: In Main.vb (module file) ``` Public WithEvents foo As VarType1 ``` In Someform.vb (Windows Form) ``` Private Sub fooEventHandler(sender as System.Object, e As fooEventArgs) Handles foo.fooEvent ``` I get an error that says "Handles clause requires a WithEvents variable defined in the containing type or one of its base types". Isn't this what I've done? Or am I missing something?

Original source