Accessing Properties/Methods of a Page through an embedded UserControl

Sometimes it’s necessary to access a method/property on a Page from the UserControl code.

Eg.

We have a Page that has a label on it. A UserControl is embedded in that page. The UserControl has a DropDownList of values. When the value in the DropDownList is changed, we want the UserControl to change the value of Page’s label to reflect the selected value of the drop down list.

Now because the UserControl is associated with the Page using aggregation and there is no reference back to the Page instance it becomes a little tricky to do this.

We could pass a reference to the label in the UserControl but once we do that, we are creating a tighter coupling between the Page and UserControl thus making it difficult to re-use the UserControl for Pages that don’t have a label that needs modification.

Don’t worry though! The Event Handler (or Observer) pattern is very handy and comes into play to enable a communication mechanism that gets around the coupling problem.

In the UserControl declare a public property that accepts and returns an EventHandler delegate.

Eg.



public class ExampleUserControl : UserControl {

	protected DropDownList automobileTypes;
	private EventHandler automobileChangeHandler;

	public EventHandler AutomobileChangeHandler {
		get { return automobileChangeHandler; }
		set { automobileChangeHandler = value; }
	}

Now call the declared EventHandler at the appropriate execution point.

Eg.



	...
        ...

	private void InitializeComponent() {
 	     this.Load += new System.EventHandler(this.Page_Load);
             automobileTypes.SelectedIndexChanged += new EventHandler(automobileTypes_SelectedIndexChanged);
	}

	private void automobileTypes_SelectedIndexChanged(object sender, EventArgs e) {
		if (AutomobileChangeHandler != null) {
			AutomobileChangeHandler(automobileTypes.SelectedValue, e);
		}

	}

In the Page class create a method to be executed by the UserControl’s event handler. Define the logic that the UserControl’s event is to trigger on the Page object.

Eg.



public class ExamplePage : Page {

	protected Label name;
	protected ExampleUserControl euc; 

	private void ExampleUserControl_Changed(object sender, EventArgs e) {
		name.Text = String.Format("You have selected - {0}", sender as string);
	}

        override protected void OnInit(EventArgs e) {
		InitializeComponent();
		base.OnInit(e);
	}

	private void InitializeComponent() {
		this.Load += new System.EventHandler(this.Page_Load);
		euc.AutomobileChangeHandler += new EventHandler(ExampleUserControl_Changed);
	}

	#endregion
}

Thus allowing a UserControl to trigger events in the page object, without explicitly knowing about the class in which the UserControl resides.

Posted in .Net, Asp.Net, C#, Development by Ben at December 6th, 2006.

2 Responses to “Accessing Properties/Methods of a Page through an embedded UserControl”

  1. Gerrod says:

    You should actually be declaring your EventHandler property in the user control like this -

    public event EventHandler AutomobileChangeHandler;

    This also saves you from having to explicitly create a property for the AutomobileChangeHandler.

    The reason that you’re supposed to do it like this is because the “event” keyword hides the complexity of event registration and de-registration. But, you can explicitly implement your own storage mechanism for event handlers, similar to how you create a property – except instead of “get” and “set”, you use “add” and “remove” –

    
    private IList handlers = new List();
    public event EventHandler AutomobileChangeHandler {
        add {  handlers.Add(value); }
        remove { handlers.Remove(value); }
    }
    

    Obviously, using the += and -= notation is the shorthand way of calling the add and remove properties of an event.

  2. ben says:

    All good points my friend.

    I originally wrote the article using a delegate instead of the EventHandler and didn’t think to go the whole hog when changing over.

    Thanks for the pickup.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Quickduck logo