Click here to Skip to main content
15,894,405 members
Articles / Programming Languages / C#
Article

Populating a drop down control from an XML file

Rate me:
Please Sign up or sign in to vote.
2.88/5 (13 votes)
26 Feb 2004 63.3K   13  
This article describes a simple way to populate a drop down control from an XML file.

Introduction

This small snippet of code will show you how to populate a drop down list of a combo box from an XML file.

Code

Step 1: Add a combo box control to a form or a web page.

Step 2: Create an XML file with the following structure and save it as att.xml.

XML
<Root>
 <Field text="User friendly text" value="Value for the text"></Field>
 ...
 ...
</Root>

There will be a <Field> tag for item that needs to be displayed in the drop down list. The text attribute will store the user friendly text to be displayed in the combo box and the value attribute will store the actual selected value.

The drop down will be populated by reading the XML into a DataSet and then binding the drop down to the DataSet. The sample code to read an XML with attributes into a DataSet is shown below:

C#
private void InitializeDropDown()
{
  DataSet ds = new DataSet();
  DataTable dt = new DataTable("Root");
  ds.Tables.Add(dt);
  dt.Columns.Add("text");
  dt.Columns.Add("value");
  // specify that the values will be read from
  // the attributes and not from an element in the XML file
  foreach (DataColumn dc in dt.Columns)
  {
    dc.ColumnMapping = MappingType.Attribute;
  }
  // replace the file path with the actual file path
  FileStream myFileStream = new FileStream("C:\\att.xml", 
                            FileMode.Open, FileAccess.Read);
  StreamReader myXmlStream = new StreamReader(myFileStream);
  ds.ReadXml(myXmlStream);
  myFileStream.Close();
  DataGrid1.DataSource = ds.Tables[0];
  DataGrid1.DataBind();
}

Step 3: Call the method above, from the constructor or page_load event.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --