I am creating a custom control. Let's say I'm reinventing the wheel and creating a custom Button control that derives from the UserControl class(only for example)
Well, it of course has a Click
event h开发者_高级运维andler. Now my problem is, when do I call this event handler? I know it happens sometime between the Pages OnLoad and OnLoadComplete, but I'm not quite sure what event I can hookup to so that the Click
event is raised at the same time as other control events.
When are you suppose to call custom control events?
In general you should raise the event as soon as you know that the underlying event has happened.
For example, how does the ASP.NET Button control know that the it was clicked by the use? It implements IPostBackEventHandler and the RaisePostBackEvent() method. That method will get called if there is postback event data associated with the control. I believe the association is determined by the "name" attribute that it renders. In RaisePostBackEvent() it then raises the Click event.
The question you need to answer is: How does your control know that it should raise its event? Once you find that our the rest is easy.
If your control has similarities to existing ASP.NET controls I would recommend stepping through the ASP.NET source code and seeing how those controls work.
If you implement IPostbackEventHandler
, you can do something like this, taken from decompiling System.Web.Ui.WebControls.Button
protected virtual void RaisePostBackEvent(string eventArgument)
{
base.ValidateEvent(this.UniqueID, eventArgument);
if (this.CausesValidation)
{
this.Page.Validate(this.ValidationGroup);
}
this.OnClick(EventArgs.Empty);
this.OnCommand(new CommandEventArgs(this.CommandName, this.CommandArgument));
}
精彩评论