Read and Bind XML File to ASP.Net DropDownList Control
 
Author:
Filed Under: ASP.Net  |  C#.Net  |  VB.Net  |  XML
Published Date: Jun 13, 2010
Views: 4565
 

Abstract: Here Mudassar Ahmed Khan has explained how to bind an XML or XML File to ASP.Net DropDownList Control using DataSet in C# and VB.Net

Comments:  2

 

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#
using System.Data;
VB.Net
Imports System.Data
 
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









Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit