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# and create a new Windows Forms Application named XmlListUpdate1
  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. Save this XML file in your bin\Debug folder
  7. 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
  8. Double-click the Add button and implement its Click event as follows:
    private void btnAdd_Click(object sender, System.EventArgs e)
    	string NewItem = this.txtFlavor.Text;
    	// If there is no flavor to add, do nothing
    	if( NewItem == "" )
    	// 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(NewItem + " exists already in the list and will not be added.");
    	// Since the item is not yet in the list, add it...
    	// After adding the item to the combo box, remove it from the text box
    	this.txtFlavor.Text = "";
    	// And give focus to the text box in case the user wants to add another item
  9. In the using namespace section on top of the file, add the following two lines:
    using System.Xml;
    using System.Text;
  10. Double-click an empty area on the form and implement its Load event as follows:
    private void Form1_Load(object sender, System.EventArgs e)
    	// Declare a variable of type  XmlTextReader
    	 XmlTextReader xtr  = null;
    	 // Declare a string that holds the name of the file
    	 string fileName = "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 != null)
  11. Click an empty area on the form. Then, in the Properties window, click the Events button
  12. Double-click the Closing field and implement its event as follows:
    private void Form1_Closing(object sender,
      System.ComponentModel.CancelEventArgs e)
    	XmlTextWriter xtw = null;
    	string fileName   = "ISFlavors.xml";
    	 try {
    		 xtw = new XmlTextWriter(fileName, Encoding.UTF8);
    		 xtw.Formatting = Formatting.Indented;
    		 for(int i = 0; i < this.cboFlavors.Items.Count; i++)
    		 if (xtw != null)
    private void btnClose_Click(object sender, System.EventArgs e)
  13. Test the application


Home Copyright © 2004-2010 FunctionX, Inc.