Logo

Combo Box Items From an XML File

 

Introduction

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"?>
    <flavors>
      <flavor>French Vanilla</flavor>
    </flavors>
  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 == "" )
    		return;
    
    	// 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.");
    		return;
    	}
    
    	// Since the item is not yet in the list, add it...
    	this.cboFlavors.Items.Add(NewItem);
    	// 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
    	this.txtFlavor.Focus();
    }
  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
    				 this.cboFlavors.Items.Add(xtr.Value);
    				 break;
    			 }       
    		 }
    
    		 // For this example, select the first item
    		 this.cboFlavors.SelectedIndex = 0;
    	 }
    	 finally
    	 {
    		 // Close the XmlTextReader
    		 if (xtr != null)
    			 xtr.Close();
    	 }
    }
  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;
    
    		 xtw.WriteStartDocument();
    		 xtw.WriteStartElement("flavors");
    
    		 for(int i = 0; i < this.cboFlavors.Items.Count; i++)
    		 {
    		xtw.WriteElementString("flavor", 
    			 (string)this.cboFlavors.Items[i]);
    		 }
    
    		 xtw.WriteEndElement();
    		 xtw.WriteEndDocument();
    	 }
    	 finally
    	 {
    		 if (xtw != null)
    			 xtw.Close();
    	 }
    }
    
    private void btnClose_Click(object sender, System.EventArgs e)
    {
    	Close();
    }
  13. Test the application

 


Home Copyright © 2004-2010 FunctionX, Inc.