Thursday, April 12, 2012

Write custom events for User Controls in ASP.NET

Often we need some code to be executed in hosting page in response to some action in User control.
Say for example, your Page is having a Country dropdown, and also placed a user control having interface to allow users to add a new country in underlying data store. What you really require is to reload your Country dropdown as soon as user adds/edits a country through the user control.

This article will explain how to write custom events in user controls and to handle them in the hosting page in order to achieve this:

A. Changes to be done in Add/Edit Country User control.
- Declare an event handler in your Country user control.
public event System.EventHandler CountryAdded;
- Jump to the "Save" button code (or ItemInserted/ ItemUpdated event, if you are using ObjectDataSource).
Add following lines after completion of Save operation code.

if (this.CountryAdded != null)
{
this.CountryAdded(this, new EventArgs());
}

This is all you need to do in User control to make the control responsive to "CountryAdded" event.

B. The last step is a very straight forward - Just write event handler in your hosting page, and there you need to rebind your DropDownList.

Once done, you should now be able to see Country dropdown in your page gets reloaded as and when a Country is added/ edited through User control on that page.

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive