Let’s say your custom control has a state to maintain between the page postbacks. Meaning, if the user clicks on some other control and the page is submitted to server, the page would eventually come back with a refresh. At this refresh, your custom control shouldn’t lose its state.
For example, if your control is a web editor, the editor should still have the latest text that the user entered after the refresh. If you developed a polling control, it should have the latest poll option that the user selected once the refresh has been finished.
IPostBackDataHandler Methods
To do this, you would implement the IPostBackDataHandler methods. You would do the following methods:
#region IPostBackDataHandler Members
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
...
}
public void RaisePostDataChangedEvent()
{
...
}
public event EventHandler TextChanged;
protected virtual void OnTextChanged(EventArgs e)
{
...
}
#endregion
Page need to know about PostBack requirement
The issue this article deals with is: Even after doing the above (i.e. implementing all the required methods above), you are still having problems -- the control is losing state after the postback (i.e. the web editor has lost the text after refresh, etc.)
You need to do one more thing: your custom control must tell the page that it needs postback handling. You do this by RegisterRequiresPostBack method that is available on the Page.
Page.RegisterRequiresPostBack(this);
Obviously, you don’t want to do this from the page that’s including this custom control. That’s work for the developer using this custom control. This registration can occur before the custom control has been rendered on the page. So, this line can be in the OnPreRender event handler.
/// <summary>
/// Register RequiresPostBack
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Page != null)
Page.RegisterRequiresPostBack(this);
}
With the above inlcusion, the IPostBackDataHandler methods like LoadPostData() will be executed. If you include state management code there (like copying the posted data back into the custom control), your control will retain the state after page refresh.