Search This Blog

Wednesday, December 22, 2010

How to bind or populate Dropdownlist from XML file

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:



<Products>
<Product>
<ID>1ID>
<Name>Product 1Name>
Product>
<Product>
<ID>2ID>
<Name> Product 2Name>
Product>
<Product>
<ID>3ID>
<Name> Product 3Name>
Product>
<Product>
<ID>4ID>
<Name> Product 4Name>
Product>
<Product>
<ID>5ID>
<Name> Product 5Name>
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.

No comments:

Post a Comment

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