Wednesday, November 28, 2012

Bind asp.net dropdownlist to xml file


Today I was working on binding the dropdown list control from an  XML file. Besides binding the dropdown list from XML file I had to sort the items into ascending order. So I am explaining here what I have done for this.

Let’s define an  XML file first. It consists of Department name of a company.


<?xml version="1.0" encoding="utf-8" ?>
<Departments>
  <Department>
    <DepartmentName>HR</DepartmentName>
    <DepartmentCode>1</DepartmentCode>
  </Department>
  <Department>
    <DepartmentName>Operations</DepartmentName>
    <DepartmentCode>2</DepartmentCode>
  </Department>
  <Department>
    <DepartmentName>Accounts</DepartmentName>
    <DepartmentCode>3</DepartmentCode>
  </Department>
</Departments>

We place this xml file in the Resources folder of the root of our solution. Now let us define the markup for the asp.net dropdownlist control.

<table width="100%" border="0">
  <tr>
    <td>
     <asp:Label ID="lblDepartment" runat="server" Text="Select Department :" Font-Bold="true"></asp:Label>
    </td>
    <td>
      <asp:DropDownList ID="drpDepartment" runat="server" Width="150px">
      </asp:DropDownList>
    </td>
  </tr>
</table>


Now in the load event of the page, we read the xml file into a dataset. We will get the Data View for the default table in the dataset, and sort it. The table will consists of as many rows as there are department objects in the xml file. Each row has two columns: DepartmentCode and DepartmentName. Now we can bind this dataview to the dropdownlist control, as in the code (in C#) below.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
           this.BindDDLFromXML();
     }
 }
 private void BindDDLFromXML()
 {
        DataSet dsDepartment = new DataSet();

        //read in xml file in dataset
        dsDepartment.ReadXml(MapPath("~/DepartmentXML.xml"));

        //get the dataview of table "Department", which is default table name 
        DataView dvDepartment = dsDepartment.Tables["Department"].DefaultView;

        //Now sort the DataView by column name "DepartmentName"
        dvDepartment.Sort = "DepartmentName";

        //now define datatext field and datavalue field of dropdownlist 
        drpDepartment.DataTextField = "DepartmentName";
        drpDepartment.DataValueField = "DepartmentCode";

        //now bind the dropdownlist to the dataview 
        drpDepartment.DataSource = dvDepartment;
        drpDepartment.DataBind();
  }

That’s simple!!
Happy programming!! :)

No comments:

Post a Comment

^ Scroll to Top