Sunday 13 January 2013

Read Xml file in DropDownList in asp.net using c#.


In this post I will explain how to read XML file in DropDownList in asp.net using c#.

Description:-


I have written many post regarding DropDownList. In this post I will explain how to read a xml file in DropDownList or how to bind xml data to DropDownList. For this first Create an xml file and put some dummy data in it.

Create a xml file name Employee.xml and insert some data in this file.

Employee.xml:-

<?xml version="1.0" encoding="utf-8" ?>
<employees>
  <employee>
    <EmpName>Sushil Kumar</EmpName>
    <EmailId>Sushilct25@gmail.com</EmailId>
    <Designation>Engg.</Designation>
    <PhoneNo>9998882345</PhoneNo>
  </employee>
  <employee>
    <EmpName>Prdeep Kumar</EmpName>
    <EmailId>pradeep@gmail.com</EmailId>
    <Designation>Manager</Designation>
    <PhoneNo>12344567890</PhoneNo>
  </employee>
  <employee>
    <EmpName>sushil Modi</EmpName>
    <EmailId>modi@gmail.com</EmailId>
    <Designation>Soft. Developer</Designation>
    <PhoneNo>224525426</PhoneNo>
  </employee>
  <employee>
    <EmpName>Rahul Ranjan</EmpName>
    <EmailId>ranjan@gmail.com</EmailId>
    <Designation>Engg.</Designation>
    <PhoneNo>1245225</PhoneNo>
  </employee>
  <employee>
    <EmpName>Chulbul Pandey</EmpName>
    <EmailId>pandey@gmail.com</EmailId>
    <Designation>Economist</Designation>
    <PhoneNo>235235353</PhoneNo>
  </employee>
</employees>

After that add a web page to the project and drag  a dropdownlist on this page like this..

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

After that add the following namespace  in codebehind:-

using System.Data;
using System.Xml;

Code behind page:-

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }
    public void BindDropDownList()
    {
        XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("Employee.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlReader);
        xmlReader.Close();
        if (ds.Tables.Count != 0)
        {
            DropDownList1.DataSource = ds;
            DropDownList1.DataTextField = "EmpName";
            DropDownList1.DataValueField = "EmpName";
            DropDownList1.DataBind();
        }
       
    }

         Output Like this..



If you like this post please spread this among in your friends.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.