What follows is a utility that iterates through the controls in a container and saves or restores values for the controls in an XML file. The enclosed namespace captures application data, also known as sticky data or state data. The concept is the same as the now denigrated INI file or Windows Registry. As I was preparing to post this, I chanced upon a submission by Chad Z. Hower a.k.a. Kudzu. Chad’s article accomplishes the same task using a different method, and I encourage you to read it. The process I present to you is less tightly coupled to your container class than Chad’s, but also less powerful in handling non-textual data.
Using the code
The demo project consists of three containers, a form and a tab control with two pages. Each container creates its own XML file in the same directory as the executable. To use the code, include the namespaces
PFM_Wrap_Ctrl_Value_Property in your project. There are two ways to save state data and one process to restore state data:
- The first method shown below is the easiest to use because it works for all (text-like) controls in the container. As new controls are added to the container, they become part of the solution set, by default.
- The second method allows greater programmer control but a little more effort to implement. The second method requires the programmer to be explicit about what controls are part of the solution set.
- Lastly, the third segment of code shows how to restore the XML file contents to the controls on the container.
Control.ControlCollection allControlHeldByThisContainer = this.Controls;
Control exceptionArray = new Control;
exceptionArray = radioButton1;
exceptionArray = radioButton3;
string sContainerName = this.Name.ToString();
string sTitle = this.Text;
SaveRestoreControlDefaults frmDfts =
Control desiredCtrls = new Control;
desiredCtrls = this.lblCheckListBox;
desiredCtrls = this.checkedListBox1;
string sContainerName = this.tabPage2.Name.ToString();
string sTitle = "Controls from tabpage2";
SaveRestoreControlDefaults tabDfts = new SaveRestoreControlDefaults();
tabDfts.ExplicitySaveControls(desiredCtrls, sContainerName, sTitle);
SaveRestoreControlDefaults frmDfts = new SaveRestoreControlDefaults(
Points of interest
That is it. The process of capturing and restoring information to your container is as loosely coupled as I could imagine it. It is only fair to tell you I only dabble in C# occasionally, but I have a lot of C++ experience, and I think this is a utility worth sharing.
Lastly, no part of this code was plagiarized, and you can use it as is or modify it without any restrictions. Hell, you can even put your name on it.
VB.NET source is not currently available.