Dynamically Adding Controls to a Windows Form - What Do I Need to Store?
(Page 3 of 5 )
It was okay that I didn’t have any private variables (beyond the three labels) since I didn’t need to access or manipulate any of the checkbox or textbox controls after they were created. But I realized that if I wanted to handle the mouse click events, changing the values of the numeric controls, I would need to keep around some references to the numeric up down controls. So I created a private Hashtable to store them in. I called it nudControls. Why wouldn’t I also need to store the check box controls? Well, the Mouse Up event handler looks like this:
private void cbName_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
The given sender object is the object that sent the event, in this case the checkbox control itself. More on this later.
Upon further analysis, I observed that I would need to store the vertical position of the last control I placed in the form. This would allow me to re-size the form once all of the controls were dynamically added. So I created a private int called vertPos to store that information.
Loading from XML
Next I create a private method to read the XML. Since I was only going to read the file, I decided a standard SAX parser would be sufficient. The .NET XmlTextReader class implements the SAX parser, so I was ready to go. Here is what the method looks like:
private void LoadFromXML () {
XmlTextReader xmlReader = null;
try {
//Create an instance of the XMLTextReader.
// Since we will only be reading the file, a SAX parser will do fine
xmlReader = new XmlTextReader("Medications.xml");
while (xmlReader.Read() ) {
if (xmlReader.NodeType == XmlNodeType.Element) {
// Look for "medication" tags, ignoring all others
if (xmlReader.Name == "medication") {
// Get out the "name" and "dosage attributes
string name = xmlReader.GetAttribute("name");
string dosage = xmlReader.GetAttribute("dosage");
// Create a row of dynamic controls
vertPos = CreateRow(name, dosage);
} // test for "medication" name
} // test for element node type
} // end loop through reading
} catch (XmlException ex){
System.Console.Write("An XML exception occurred: n" + ex.ToString());
} catch (Exception ex){
System.Console.Write("A general exception occurred: n" +ex.ToString());
}
finally {
if (xmlReader != null) {
xmlReader.Close();
}
}
}
For those familiar with reading XML files, the code above is familiar. After creating our xmlReader, we loop through looking for element nodes. If the element Name is equal to “medication,” we extract the “name” and “dosage” attributes, and create a row. The loop continues until all elements have been read.
Next: Creating the Controls >>
More .NET Articles
More By W. Daniel Skousen