Dynamically Adding Controls to a Windows Form - Defining the Attribute File
(Page 2 of 5 )
I started with the simplest part of my application: defining the external attribute file I would read when creating my form. The idea had XML written all over it. An XML file would allow me to define all the elements and attributes I would need, and allow for potentially validating the information against a DTD or XSD. Although I didn’t get to the validating part (an exercise for the student), the file was very straightforward. It looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<medications>
<medication name="Aspirin" dosage="50mg"/>
<medication name="Tylenol" dosage="100mg"/>
<medication name="Motrin" dosage="200mg"/>
<medication name="Aleve" dosage="75mg"/>
<medication name="Pepsid" dosage="25mg"/>
<medication name="Excedrin" dosage="300mg"/>
<medication name="Tums" dosage="500mg"/>
</medications>
Easy enough. All my common medications were there. Should one of my co-workers want to use the application for their own nefarious purposes, the name and dosage information in the XML file was easily available for them to change. I saved it in the “bin/Debug” directory so it would be available to the executable without any directory padding.
Designing the Form
I knew that I wanted my form to have three items on each row. The first would be a CheckBox control, with the text of the checkbox being the name of the medication. Second, I wanted a basic TextBox control. And lastly, I wanted a NumericUpDown control that indicated how many times I had taken the medication. I wanted something that looked like this:

Differences Between Static and Dynamic Forms
One of the more obvious things I would have to deal with when creating my form would be the simple fact that, when I add an item to a form, none of the private data members Visual Studio kindly created for me would be available. You’ve seen them, I’m sure. If I place a CheckBox on my form in the Design window, when I viewed the code, I would expect to see a line such as the following placed in my code source file:
private System.Windows.Forms.CheckBox checkBox1;
Likewise, in the InitializeComponent method (located in the hidden “Windows Form Designer” region), Visual Studio places the proper creation code for the checkbox, specifying and setting the various properties I had set in the Design window.
Alas, all of that simplicity and ease of use would be gone. The only items I “statically” placed on my form were the three labels at the top. Everything else would be added dynamically.
Next: What Do I Need to Store? >>
More .NET Articles
More By W. Daniel Skousen