Posted by Alec on Tue, 16 Jun 2009, in ASP.NET C#
UserControls are great, particularly in making the code more eye friendly, seperating big bunch of codes into different parts and be able to re-use them throughout the application. However, there are times when we need to reference something in the parent page or control from the usercontrol level. That's when I had an issue today, and finally solved it using the brilliant delegate.
Here's how it work:
Suppose I have a parent page that has these: 1. UserControl 2. Label
The UserControl itself is a web form with a number of fields. Now, what I want to do is whenever someone fills in the form (usercontrol), the result will get sent back to the parent and displayed in the label. With the use of delegate, this can be done easily:
In the usercontrol, simply create a delegate:
public delegate void FormSubmittedHandler(object sender, EventArgs e);
This has to be outside the class.
Then, also create an event handler:
public event FormSubmittedHandler Changed; protected virtual void FormSubmitted(object sender, EventArgs e) { this.Title= txbTitle.text; if (Changed != null) Changed(this, e); }
This event handler will update the usercontrol's properties and then publish to its subscribers (which is the parent). We could call this event handler whenever we want, for example when the submit button is clicked or ontextchanged if you are using Ajax.
In the parent, which is the subscriber, we need to fetch the data and do something: protected void Page_Init(object sender, EventArgs e) { usercontrolWebForm.Changed += new FormSubmittedHandler (updateLabel); } protected void updateLabel(object sender, EventArgs e) { this.txbLabel = usercontrolWebForm.Title; }
How nice and easy that is?