Click here to Skip to main content
Licence 
First Posted 26 Feb 2004
Views 40,906
Bookmarked 12 times

Populating a drop down control from an XML file

By | 26 Feb 2004 | Article
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.

<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:

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

About the Author

nikhilt

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 27 Feb 2004
Article Copyright 2004 by nikhilt
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid