Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Binding an dropdownlist with an XML file - Part 18

Suggested Videos
Part 15 - Command Event of an button control
Part 16 - DropDownList in
Part 17 - Data bind dropdownlist with data from the database

In Part 17 of this video series we have discussed about binding a DropDownList to data that is retrieved from a database. In this part, we will learn about binding the DropDownList to Data from an XML file.

First add an XML file, to the web application project. To do this 
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>

Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
        //Create a new DataSet
        DataSet DS = new DataSet();
        //Read the xml data from the XML file using ReadXml() method
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryId";
        DropDownList1.DataSource = DS;
        ListItem li = new ListItem("Select", "-1");
        DropDownList1.Items.Insert(0, li);

The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet. Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.

To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.

No comments:

Post a Comment

It would be great if you can help share these free resources