Messaging Between Forms

Messaging Between Forms

Messaging between forms is the most robust way of passing data back and forth between forms. It allows you to create forms that can be re-used with a minimum of issues about how you connect data on different forms.

Messaging between forms involves creating an Event and adding code to raise the event on the sending form, and creating an event handler to receive the message on the receiving form. It seems complex at first, but once you have used the code a few times it becomes quite simple.

An event is created (‘declared’ would be a better term) using the Event keyword with the event name and signature. In this example the event name is ValueChangeEvent. The signature in this example is a Double and a String (the value and the warning message). The RaiseEvent keyword raises the event so that it is broadcast to any object that is listening for it.

The listening form needs to create an event handler routine that processes the event arguments. The event handler is simply a SUB that contains the code to be executed when the event occurs. The signature of this event (a Double and a String in the example) must match the signature in the event declaration. The listening form uses the AddHandler keyword to associate the event with the event handling routine. The result is that when the event occurs, the code in the event handler will be executed.

This example assumes that the form being created needs to send a message back to the form that created it.

In the form that will be raising the event (the sender) the code would look like this:

The RaiseEvent instruction creates and sends a message with the supplied arguments (TempValue and TempComment). When the event is raised, it is is handled by any listeners that have been connected to it – in this case the ValueChangeHandler routine, and the controls will be updated with the values passed to the event handler.

This process would be considered robust because the form that is created can function without knowing anything about the process by which it was created. It does not need a reference to the form that it is sending the information to. It will raise the messages when the value changes, but it is entirely the responsibility of the other form(s) to instal a handler for those messages and to process them. If those other objects don’t need those messages, they simply don’t add the handler.