Here I am explaining how to bind an XML fine to ASP.Net DropDownList control.
XML file
Below is my Cities.xml which I contains the list of some Indian cities.
<?xmlversion="1.0"encoding="utf-8" ?>
<cities>
<city>
<id>1</id>
<name>Mumbai</name>
</city>
<city>
<id>2</id>
<name>Delhi</name>
</city>
<city>
<id>3</id>
<name>Chennai</name>
</city>
<city>
<id>4</id>
<name>Kolkatta</name>
</city>
</cities>
The name
of the City will be assigned to the Text part and the id will be assigned to the Value part of the ASP.Net DropDownList Control.
Namespace
You will need to import the following namespace.
C#
VB.Net
Reading the XML file and Binding the DropDownList
Below is the method that reads the XML file into a Dataset object and then binds the same to the ASP.Net DropDownList Control
C#
private void BindXml()
{
string filePath = Server.MapPath("~/Cities.xml");
using (DataSet ds = new DataSet())
{
ds.ReadXml(filePath);
ddlCities.DataSource = ds;
ddlCities.DataTextField = "name";
ddlCities.DataValueField = "id";
ddlCities.DataBind();
}
}
VB.Net
Private Sub BindXml()
Dim filePath As String = Server.MapPath("~/Cities.xml")
Using ds As DataSet = New DataSet
ds.ReadXml(filePath)
ddlCities.DataSource = ds
ddlCities.DataTextField = "name"
ddlCities.DataValueField = "id"
ddlCities.DataBind()
End Using
End Sub
I am calling the above method in the Page Load event of the Page in the following way
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindXml();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindXml()
End If
End Sub
This completes this article. You can download the source code in VB.Net and C# using the link below
BindingXMLtoDropDownList.zip