Oct 27, 2015

Binding an asp.net dropdownlist with an XML file

First add an XML file, to the web application project. To do this 
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <CountryId>101</CountryId>
    <CountryName>India</CountryName>
  </Country>
  <Country>
    <CountryId>102</CountryId>
    <CountryName>US</CountryName>
  </Country>
  <Country>
    <CountryId>103</CountryId>
    <CountryName>Australia</CountryName>
  </Country>
  <Country>
    <CountryId>104</CountryId>
    <CountryName>UK</CountryName>
  </Country>
</Countries> 


Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create a new DataSet
        DataSet DS = new DataSet();
        //Read the xml data from the XML file using ReadXml() method
        DS.ReadXml(Server.MapPath("Countries.xml"));
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryId";
        DropDownList1.DataSource = DS;
        DropDownList1.DataBind();
        ListItem li = new ListItem("Select""-1");
        DropDownList1.Items.Insert(0, li);
    }
}

The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet.Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.

To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.

No comments:

Post a Comment