Home > ASP.Net, XML > Bind DropdownList from XML file

Bind DropdownList from XML file


Hi

try this example to Bind DropdownList from xml file on server

1) Open VS 2005 and create new website

2) Add new xml file “XMLFile.xml”

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <ID>1</ID>
    <Name>Nepal</Name>
  </Country>
  <Country>
    <ID>2</ID>
    <Name>India</Name>
    <Country>
      <ID>3</ID>
      <Name>China</Name>
    </Country>
    <Country>
      <ID>4</ID>
      <Name>Bhutan</Name>
    </Country>
    <Country>
      <ID>5</ID>
      <Name>USA</Name>
    </Country>
  </Country>
</Countries>

3) Add new Web page and inside it add DropdownList control

4) In Code behind add the following code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    public void Bind()
    {
        DataSet ds = new DataSet(); 
        ds.ReadXml(Server.MapPath("~/XMLFile.xml")); 
 
        //get the dataview of table "Country", which is default table name 
        DataView dv = ds.Tables[0].DefaultView; 

        //Now sort the DataView vy column name "Name" 
        dv.Sort = "Name"; 
        //now define datatext field and datavalue field of dropdownlist 
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID"; 
 
        //now bind the dropdownlist to the dataview 
        DropDownList1.DataSource = dv;
        DropDownList1.DataBind(); 
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
}

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, XML
  1. May 12, 2012 at 8:53 am

    XMl file can be of different formats , read Bind Dropdownlist to XML for more info

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: