Thursday, January 31, 2008

Tip: How to enable post back from a custom web control?

In many scenarios I came across the need to use the __doPostBack function to do a post back for my web control or asp page. In order to do so, I have to inherit the control or page from the IPostBackEventHandler interface. However, this is not sufficient because the __doPostBack function will not be generated by the .NET FW. I have to add the "GetPostBackEventReference" function inside my control or page. The sample code below shows a simple implementation:


public classs MyControl: WebControl, IPostBackEventHandler
{
........
protected override void OnInit(EventArgs e)
{
PostBackOptions options = new PostBackOptions(this);
options.ClientSubmit = true;
Page.ClientScript.GetPostBackEventReference(options);
}
}


This enables the implementation of the following user functions:
1. Pass back key press from user computer back to server.
2. Any scenarios that require __doPostBack to be called manually in code.

No comments: