Craig Gibbons' Lifeblog lifeblog://tri.eat.net

15Mar/050

Raising events from a Web User Control

One of the more advanced topics in ASP.NET is that of communication between a page and the controls it contains. There are various approaches to this problem and some methods work better in some circumstances than others. Sometimes however, it is necessary to take action in a page based on an action performed in a user control, such as a button being clicked, a dropdown posting back or any number of other possible events that can be raised. This sounds quite daunting at first, especially if you come from a non-OO background or otherwise are not used to working with events, but it really is very powerful and in fact not very difficult to master. Let's take a common scenario where a page contains a single Web User Control and we wish to respond to a button click in that control. The explanation of the code is quite involved, so the reader will have to cope with the following code example.

First off, we need to register the event in the user control. This is done in the same way you would declare any variable:

public event EventHandler ButtonClicked;

Then, we need a pair of functions to handle and then bubble the event to the container page:

protected void btnButton_Click(object sender, System.EventArgs e) {
OnButtonClicked(sender, e);
}

public void OnButtonClicked(object sender, EventArgs e) {
if(ButtonClicked != null) {
ButtonClicked(sender, e);
}
}

That’s all that needs to be done on the control side. Now all we have to do is write an event handler on the page and voila! We have raised and handled an event from a user control. You do this in the same way you write any event handler, just let the IntelliSense help you along. Yup, .NET rocks!

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.