5.4. Communicating Between User Controls

Problem

You have multiple user controls on a page, and one of the user controls needs to send data to another as, for example, when one control takes its form or content from the user’s action on another.

Solution

Create a custom event argument class to define the message to be sent, a source user control, a destination user control, and a web form that contains both user controls. (See Recipes 5.1 and 5.2 for detailed steps.)

In the custom event argument class that defines the message to be sent:

  1. Inherit from EventArgs.

  2. Add a message property to contain the message data.

In the source user control:

  1. Create a custom event.

  2. Raise the event when the required action is performed, such as when a user completes her entry for a form.

In the destination user control:

  1. Create an event handler to receive the event from the source user control.

  2. Display the message received.

In the web form used to test the user control communication:

  1. Add the source user control.

  2. Add the destination user control.

  3. “Wire” the event raised in the source user control to the event handler in the destination user control in the Page_Load event of the web form.

The output of a test page showing one user control communicating with another appears in Figure 5-4. The code for our example application that implements the solution is shown in Examples 5-15, 5-16, 5-17, 5-18, 5-19, 5-20, 5-21, 5-22, 5-23, 5-24 through 5-25. Examples 5-15 (VB) and 5-16 (C#) show the custom event argument class ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.