Combo Box Items From an XML File



When discussing file processing, we mentioned that it is sometimes necessary to automatically save a file when an application exits, without any intervention from the user. You can also solve this exact problem using XML. The ever growing strength of XML is in its ability to let modify a file however but still make that file usable by any environment that needs its content.

We are going to create an XML file that holds a list of items for a combo box. Once the file exists, it can be processed or modified by any application that can read XML. We will load the file automatically when the application opens and retrieve the values of the elements to complete a combo box. While using the application, we will allow the user to change the list. When the application closes, we will retrieve the list of items from the combo box and update (in reality) recreate the list that includes the new items.


Practical Learning: Using XML Values

  1. Start Visual C++ .Net and create a new Windows Forms Application named XmlListUpdate
  2. To create an XML file, on the main menu, click Project -> Add New Item...
  3. In the Templates list, click XML File (.xml)
  4. In the Name box, replace the string with ISFlavors and click open
  5. Change the contents of the file as follows:
    <?xml version="1.0" encoding="utf-8"?>
      <flavor>French Vanilla</flavor>
  6. Design the form as follows:
    Control Text Name Other Properties
    Label Flavor    
    ComboBox   cboFlavors DropDownStyle: DropDownList
    Sorted: True
    Button Add btnAdd  
    TextBox   txtFlavor  
    Button Close btnClose  
    Form     AcceptButton: btnAdd
    StartPosition: CenterScreen
  7. Double-click the Add button and implement its Click event as follows:
    /// <summary>
    		/// This method is used to add a new item to the list.
    		/// The item must be typed in the accompanying text box
    		/// When the user clicks Add, the compiler checks if the item already exists in the list.
    		/// If it does, the item is not added.
    		/// </summary>
    	private: System::Void btnAdd_Click(System::Object *  sender, System::EventArgs *  e)
    				 String *NewItem = this->txtFlavor->Text;
    				 // If there is no flavor to add, do nothing
    				 if( NewItem->Equals(S"") == true )
    				 // Since there is an item to add, prepare to add it
    				 // First make sure the item is not already in the list
    				 if( this->cboFlavors->FindStringExact(NewItem) > 0 )
    		MessageBox::Show(String::Concat(NewItem, S" exists already in the list and will not be added."));
    				 // Since the item is not yet in the list, add it...
    				 this->cboFlavors->Items->Add(__try_cast<String *>(NewItem));
    				 // After adding the item to the combo box, remove it from the text box
    				 this->txtFlavor->Text = S"";
    				 // And give focus to the text box in case the user wants to add another item
  8. In the using namespace section on top of the file, add the following two lines:
    using namespace System::Xml;
    using namespace System::Text;
  9. Double-click an empty area on the form and implement its Load event as follows:
    /// <summary>
    			 /// This event opens an existing XML file. It then checks its elements.
    			 /// It retrieves the value of each element and uses them to fill out the combo box
    			 /// In this example, we don't check whether the file exists or not.<br>
    			 /// We simply assume that it exists.
    			 /// </summary>
    private: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
    			 // Declare a variable of type  XmlTextReader
    			 XmlTextReader *xtr  = 0;
    			 // Declare a string that holds the name of the file
    			 String *fileName = S"ISFlavors.xml";
    			 try {
    				 // Initialize the XmlTextReader variable with the name of the file
    				 xtr = new XmlTextReader(fileName);
    				 xtr->WhitespaceHandling = WhitespaceHandling::None;
    				 // Scan the XML file
    				 while (xtr->Read())
    					 // every time you find an element, find out what type it is
    					 switch (xtr->NodeType)
    					 case XmlNodeType::Text:
    						 // If you find text, put it in the combo box' list
    				 // For this example, select the first item
    				 this->cboFlavors->SelectedIndex = 0;
    				 // Close the XmlTextReader
    				 if (xtr!=0)
  10. Click an empty area on the form. Then, in the Properties window, click the Events button
  11. Double-click the Closing field and implement its event as follows:
    		 /// <summary>
    		 // When the form closes, create an XML file using the items in the combo box
    		 /// </summary>
    private: System::Void Form1_Closing(System::Object *  sender, System::ComponentModel::CancelEventArgs *  e)
    			 XmlTextWriter *xtw = 0;
    			 String *fileName   = S"ISFlavors.xml";
    			 try {
    				 xtw = new XmlTextWriter(fileName, Encoding::UTF8);
    				 xtw->Formatting = Formatting::Indented;
    				 for(int i = 0; i < this->cboFlavors->Items->Count; i++)
    			xtw->WriteElementString(S"flavor", __try_cast<String *>(this->cboFlavors->Items->Item[i]));
    				 if (xtw!=0)
    private: System::Void btnClose_Click(System::Object *  sender, System::EventArgs *  e)
  12. Test the application

Home Copyright © 2004-2010 FunctionX, Inc.