Monday, December 28, 2009

Binding DropDown from XML data Files

Let us define the xml file first. This consists of Country object with properties ID and Name.




1
Nepal


2
India

3
China


4
Bhutan


5
USA




Select from the list of countries:


Now in the load event of the page, we read the items from the xml file into a dataset. We will get the DataView for the default table in the dataset, and sort it. The table will consists of as many rows as there are country objects in the xml file. Each row has two columns: ID and Name. Now we can bind this dataview to the dropdownlist control, as in the code (in C#) below.
view plainprint?

//page load event handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//call to the function to populate dropdownlist from xml
PopulateDDLFromXMLFile();
}
}

//populates the dropdownlist from xml file
public void PopulateDDLFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/Resources/XMLFile.xml"));

//get the dataview of table "Country", which is default table name
DataView dv = ds.Tables["Country"].DefaultView;
//or we can use:
//DataView dv = ds.Tables[0].DefaultView;

//Now sort the DataView vy column name "Name"
dv.Sort = "Name";

//now define datatext field and datavalue field of dropdownlist
ddlCountry.DataTextField = "Name";
ddlCountry.DataValueField = "ID";

//now bind the dropdownlist to the dataview
ddlCountry.DataSource = dv;
ddlCountry.DataBind();
}

That simple!
Good Luck!