// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
Google / Android
Python / IronPython
SQL Server
Making sure the custom control state is saved
Your custom control events might not fire properly without RegisterRequiresPostBack method. And it would keep on losing its state.
Table of Contents

IPostBackDataHandler Methods

Page need to know about PostBack requirement


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)

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.


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)
    if (Page != null)

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.

Bookmark and Share This

More Articles With Similar Tags
When you are constructing a custom control, one of the first decisions to make is the base class to be used for the custom control class. You have a few different options for the base class. This article looks at choosing between Control and WebControl as the base class.
About  Contact  Privacy Policy  Site Map