Step 1: Creating the Required XML File named 'Countries.xml'.
- <?xml version="1.0" encoding="utf-8" ?>
- <Countries>
- <Country>
- <CountryID>1</CountryID>
- <CountryName>India</CountryName>
- </Country>
- <Country>
- <CountryID>2</CountryID>
- <CountryName>USA</CountryName>
- </Country>
- <Country>
- <CountryID>3</CountryID>
- <CountryName>China</CountryName>
- </Country>
- <Country>
- <CountryID>4</CountryID>
- <CountryName>Australia</CountryName>
- </Country>
- <Country>
- <CountryID>5</CountryID>
- <CountryName>United Kingdom</CountryName>
- </Country>
- <Country>
- <CountryID>6</CountryID>
- <CountryName>Brazil</CountryName>
- </Country>
- </Countries>
Step 2: Drag and Drop a Dropdownlist Control from ASP.NET Controls Toolbox and Press F7 Key to Add the Below code to the Code Behind File.
- using System;
- using System.Data;
- using System.Web.UI.WebControls;
- namespace DDLPopulateWithXML
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- DataSet ds = new DataSet();
- ds.ReadXml(Server.MapPath("Countries.xml"));
- Get the Correct path of the XML File
- DropDownList1.DataSource = ds;
- DropDownList1.DataTextField = "CountryName";
- DropDownList1.DataValueField = "CountryID";
- DropDownList1.DataBind();
- ListItem LI = new ListItem("---Select---", "-1");
- DropDownList1.Items.Insert(0,LI);
- on Top
- }
- }
- }
- }