O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 used ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required