Adding a 'ValueChangedOnPostback' property to TextBox, DropDownList, CheckBox, RadioButton, etc.
For my current project I'm building a framework that automatically saves all form-data on a page postback. Because a save-operation is time consuming, I want the framework only to save the information when the user really changed the data on the page.
For this, the ASP.NET framework offers a 'changed' event for each editor (TextBox, DropDownList, etc.) . E.g. when a user has changed the value in a textbox, the TextChanged event will be fired somewhere after the Page_Load and before the Page_OnPreRender event. This basically was my problem: I needed to know if the textbox was changed in the Page_Load eventhandler, not after. The TextChanged event of the TextBox just fired to late for me.
My solution was to write my own edit-controls that all inherited from their corresponding System.Web.UI.WebControls classes. All my custom edit-controls implement the IPostBackDataHandler interface, so the ASP.NET framework will call the LoadPostData method somewhere between the Init and the Load event. Also, I added my own IPostBackDataChanged interface, containing the boolean property 'ValueChangedOnPostback'. This property I can now read on the Page_Load event to know if the data of the TextBox was changed by the user.
Example code for my custom TextBox:
namespace MyProject.Web.UI.WebControls
{
public class TextBox : System.Web.UI.WebControls.TextBox, IPostBackDataHandler, IPostBackDataChanged
{
private bool _valueChangedOnPostback = false;
public bool ValueChangedOnPostback
{
get { return _valueChangedOnPostback; }
}
bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
{
string text1 = this.Text;
string text2 = postCollection[postDataKey];
if (!text1.Equals(text2))
{
this.Text = text2;
_valueChangedOnPostback = true;
}
return _valueChangedOnPostback;
}
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
this.OnTextChanged(EventArgs.Empty);
}
}
}