Introduction
I was writing a Windows application and needed to save some values displayed in a textbox. I thought it would be neat if I could encapsulate the logic for persisting textbox values in a Windows Form and have it automatically restored when the application restarts, for example in an input form.
Using the code
The main bit of logic is encapsulated in the PersistenceHelper assembly.
public Form1()
{
...
persist = new StatePersistence(this);
}
The target form calls the persistence class from its constructor and passes a reference to itself in the argument. That is all that is needed. The rest is taken care of in the PersistenceHelper library.
public StatePersistence(Form form)
{
this.form = form;
this.form.Closing +=
new System.ComponentModel.CancelEventHandler(form_Closing);
formStateFileName =
Assembly.GetExecutingAssembly().Location.Substring(0,
Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")) +
"\\" + form.Name + ".xml" ;
LoadControlValues();
}
The persistence library has only one class; StatePersistence.cs. Its constructor takes in a Form
as parameter and loads saved values from an XML file into the Form
's controls. The name of the persisted XML file is the form name + ".xml". It also subscribes to the Form
's closing event, and when invoked, it saves the Form
's controls into the XML file.
Fig 1: A sample Windows Form demonstrating persistence.
History
- 14-April-2006 - Initial version.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.