Follow by Email

Monday, April 29, 2013

Bind XML Data to Dropdown control in asp.net


Lets see how to bind XML Data to Dropdown in asp.net

1. Add a dropdrown control into your markup page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
     
    </div>
    </form>
</body>
</html>

2. Create XML Data file which will be used to bind the dropdownlist control.

<?xml version="1.0" encoding="utf-8" ?>

<Department>
  <Dept Text="--Select--" Value="0"></Dept>
  <Dept Text="IT" Value="1"></Dept>
  <Dept Text="Accounts" Value="2"></Dept>
  <Dept Text="HR" Value="2"></Dept>
</Department>

3.Now we will add XML Datasource for the dropdown control.
Go to Designer page add click on choose data source

1. Choose DataSource


2. Select XML File


3. Browse and select the XML File


4. Select Text and Value field

5. Check on Markup page, there you Should see XML Datasource control


6. Run the project and finally you should see Expected Result.

Note :
Do not use XML file with this below format as it wont work here. But It can be accessed by writing code for it in the codebehind.


<?xml version="1.0" encoding="utf-8" ?>
<Departments>
  <Dept>
    <DeptId>1</DeptId>
    <DeptName>IT</DeptName>
  </Dept>
  <Dept>
    <DeptId>2</DeptId>
    <DeptName>ACCOUNTS</DeptName>
  </Dept>
 <Dept>
    <DeptId>3</DeptId>
    <DeptName>HR</DeptName>
  </Dept>
</Departments>