June 15, 2009

ASP.NET: Attach an OnChanged Event to your own User Controls

How do you make a custom control post back to the server each time a user interacts with it? (a la OnSelectedChange in a DropDownList).
Although this sounds trivial at first I haven't found lots of resources mentionning this.

First you need to add an EventHandler to your class:


You then add the method who will launch whatever you attached to the event handler:



In your asp markup when inserting your control you can now insert the OnDateChanged property as followed:



Now for your control to AutoPostBack on a change event, you need to implement the IPostBackDataHandler interface.

As msdn describes the interface:
If you want a server control you design to examine form data that is posted back to the server by the client, you must implement the IPostBackDataHandler interface. The contract that this interface defines allows a server control to determine whether its state should be altered as a result of the post back, and to raise the appropriate events.

However even if you implement the interface and set the AutoPostBack to true, you still need to register your control as a postback control before it's rendered:


So what happens here?

Given the proper markup, the control triggers a postback if it changes. Then at postback LoadPostData is executed. That's where you implement your comparison between the present values and the posted data. Finally, if the method returns true RaisePostDataChangedEvent is executed and you call your event.
Et voilĂ !


kick it on DotNetKicks.com

No comments:

Post a Comment