Click here to Skip to main content
12,697,525 members (27,493 online)
Click here to Skip to main content
Add your own
alternative version

Stats

52.4K views
2 downloads
13 bookmarked
Posted

Populating a drop down control from an XML file

, 26 Feb 2004
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

nikhilt
Web Developer
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 27 Feb 2004
Article Copyright 2004 by nikhilt
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid