
It basically acts as a receiver for the parent page. The same is the case here.Īn important point to note here is that when we attach the event on the parent page (using += syntax), it is like we are actually adding a method, that this event will execute when it is fired. Whenever the user control finishes its task on button click, it executes the event by calling the GetDataFromChild method and the main page receives the notification in a method named ucChild_GetDataFromChild.Īs shown by the example at the start of the article, when a user subscribes to a newsletter on any website, he gets the notification emails of it. Our parent page attaches itself to this event. We create a delegate of type ChildControlDelegate and an event of the same type, on the user control. To start with, we used the combination of event and delegates. Now that we have successfully created the sample application, let's discuss how this actually works. On the clicking of the button, when we make the explicit call to the event from the user control, the parent page receives the notification through the ucChild_GetDataFromChild method.

Step 4: Run the application and click the button. Step 2: Our main page will subscribe to the event that we created on the user control, to get notification of when the event is fired on the user control. Also, declare an event on the user control, that is of the delegate type that we created. Step 1: Create a delegate on the user control, that can encapsulate a method that takes no input and returns a DateTime type. This mechanism, in our case will be the events. For this, our page must subscribe or attach itself to the user control, using some kind of mechanism. Our logic must be, to notify the parent page that some action has been performed by the user control. When a newsletter is published or some event happens on the website, the user gets an email notification of it. So for the initial setup, add a button on the user control and place the user control on the page.Ĭonsider a real-life example of when a user visits a website and subscribes to their emails for newsletters, notifications or events and so on. On the click of this button, we will send the current datetime to the parent page. This user control will have a button with an OnClick event attached to it. Our example will consist of a Default.aspx page and ChildControl.ascx user control. Being a very common requirement, I decided to discuss this requirement as an article. In order to do that, delegates are one of the most helpful ways of doing this. For example, we may need to pass data, on an OnClick event of a button on the user control, to the parent page. While using them, we often get into a situation where we need to pass some kind of data from the user control to the parent page, when any operation is performed on the user control.


Using web user controls is quite a common approach in developing web applications.
