Wednesday, July 28, 2010

How to bind or populate Dropdownlist from XML file




Please visit my new Web Site WWW.Codedisplay.com



Few days ago i got an email from one of my reader. He wants more article on XML specially on Dropdownlist. Here in this article i will explain how one can bind or populate XML data into a Dropdownlist control. Asp.net DataSet provide us a method named ReadXml where we can initially load XML file. After that we can populate Dropdownlist DataTextField & DataValueField by DataSet default view table. To do the example first add an aspx page in your project then add a Dropdownlist control. After that add an XML file like below:









<?xml version="1.0" encoding="utf-8" ?>
<Products>
  <Product>
    <ID>1</ID>
    <Name>Lux</Name>
  </Product>
  <Product>
    <ID>2</ID>
    <Name>Harpic</Name>
  </Product>
  <Product>
      <ID>3</ID>
      <Name>Dove</Name>
  </Product>
  <Product>
      <ID>4</ID>
      <Name>Sunsilk</Name>
  </Product>
  <Product>
      <ID>5</ID>
      <Name>Pentine</Name>
  </Product>
</Products>

And then under page_load event write the below code:
using System;
using System.Data;

public partial class Dropdownlist_XML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet RS = new DataSet();
            RS.ReadXml(Server.MapPath("~/ProductList.xml"));
            
            DataView dv = RS.Tables[0].DefaultView;

            //Sorting by column name "Name" defined in XML file 
            dv.Sort = "Name";

            // Set the DataTextField and DataValueField
            DropDownList1.DataTextField = "Name";
            DropDownList1.DataValueField = "ID";

            DropDownList1.DataSource = dv;
            DropDownList1.DataBind();
        }
    }
}

Run the page to see that the Dropdownlist bind data as per XML file data.

1 comments:

Anonymous said...

Well!

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash