Populating a drop down control from an XML file






2.88/5 (13 votes)
Feb 27, 2004

63571

2
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.