Monday, May 13, 2013

How to bind Dropdownlist with XML file in Asp.net


Intoduction: In this I will explain how we can bind the Dropdownlist with Xml file.
Description:
Open Visual Studio> go to File>New>Website. After that add new item and select .xml file.

Add the below mention to .xml file.

<?xml version="1.0" encoding="utf-8" ?>
<countries>
    <Country ID="-1" Name="[--Select--]"></Country>
    <Country ID="1" Name="India"></Country>
    <Country ID="2" Name="Afghanistan"></Country>
    <Country ID="3" Name="Albania"></Country>
    <Country ID="4" Name="Algeria"></Country>
    <Country ID="5" Name="America"></Country>
    <Country ID="6" Name="Andorra"></Country>
    <Country ID="7" Name="Angola"></Country>
    <Country ID="8" Name="Anguilla"></Country>
    <Country ID="9" Name="Antarctica"></Country>
    <Country ID="10" Name="Antigua and Barbuda"></Country>
    <Country ID="11" Name="Argentina"></Country>
    <Country ID="12" Name="Armenia"></Country>
    <Country ID="13" Name="Aruba"></Country>
    <Country ID="14" Name="Australia"></Country>
    <Country ID="15" Name="Austria"></Country>
    <Country ID="16" Name="Azerbaijan"></Country>
    <Country ID="17" Name="Bahamas"></Country>
    <Country ID="18" Name="Bahrain"></Country>
    <Country ID="19" Name="Bangladesh"></Country>
</countries>

Now add new webform to application. Drag and drop the dropdownlist control from Toolbox.
<asp:DropDownList ID="ddlcountry" runat="server">
        </asp:DropDownList>

After that go to Toolbox>Data>XmlDatasource.
Click on Xmldatasource>Configure Data Source.
Click on Data file>Browse >choose the .xml file and click on ok.
After that click on Dropdownlist>Choose data source.
Select the Datasource. Here I select the Xmldatasource1.
Data field to display in dropdownlist : choose/select  the field(here I select the Name)
Data field for the value of the dropdownlist: Here I choose/select the ID and click on ok.
Now see the .aspx page. It looks like as below shown:
<asp:DropDownList ID="ddlcountry" runat="server" DataSourceID="XmlDataSource1"
            DataTextField="Name" DataValueField="ID">
        </asp:DropDownList>
        <br />
        <br />
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Country.xml">
        </asp:XmlDataSource>
Now run the project and check out the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.


No comments:

Post a Comment