In this article I will explain with an example, how to populate DropDownList from XML file in ASP.Net using C# and VB.Net.
XML file
The following XML file will be used to populate the DropDownList.
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer>
<CustomerId>1</CustomerId>
<Name>John Hammond</Name>
<Country>United States</Country>
</Customer>
<Customer>
<CustomerId>2</CustomerId>
<Name>Mudassar Khan</Name>
<Country>India</Country>
</Customer>
<Customer>
<CustomerId>3</CustomerId>
<Name>Suzanne Mathews</Name>
<Country>France</Country>
</Customer>
<Customer>
<CustomerId>4</CustomerId>
<Name>Robert Schidner</Name>
<Country>Russia</Country>
</Customer>
</Customers>
HTML Markup
The following HTML Markup consists of:
DropDownList – For displaying XML File data.
<asp:DropDownList ID="ddlCustomers" runat="server"></asp:DropDownList>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Reading the XML file data and binding it to the DropDownList Control
Inside the Page_Load event handler, first the data from the XML file is read into a DataSet using its ReadXml method to which absolute path of the XML file is passed as parameter.
Then, DataTextField and DataValueField properties of DropDownList are set.
The DataSet object is assigned to the DataSource property of the DropDownList control.
Finally, the DropDownList is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (DataSet ds = new DataSet())
{
ds.ReadXml(Server.MapPath("~/Customers.xml"));
ddlCustomers.DataTextField = "Name";
ddlCustomers.DataValueField = "CustomerId";
ddlCustomers.DataSource = ds;
ddlCustomers.DataBind();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Using ds As DataSet = New DataSet()
ds.ReadXml(Server.MapPath("~/Customers.xml"))
ddlCustomers.DataTextField = "Name"
ddlCustomers.DataValueField = "CustomerId"
ddlCustomers.DataSource = ds
ddlCustomers.DataBind()
End Using
End If
End Sub
Screenshot
Demo
Downloads