Click here to Skip to main content
Click here to Skip to main content

List Control Data Binding using XML

, 13 Aug 2002
Rate this:
Please Sign up or sign in to vote.
Walks you through various alternatives to data-bind list controls, with focus on using XML.

Sample Image - xmlboundlistcontrol_screenshoot.gif

Introduction

In web development projects, we frequently need to write code to render the content of list boxes with dynamic data from a data source. In ASP-classic time, it was a relatively hard task to do. For instance, we had to query a database, retrieve a RecordSet and iterate through the RecordSet while manually creating proper HTML tags to make up the content of list box.

In ASP.NET, you could do the same thing, but there are much better ways to do that in a fraction of time. Moreover, instead of relying on a database as the data source, you can use a variety of data sources like XML files. Which one is the best? It will raise much debate around performance, flexibility, reliability, ease of deployment, security, etc., which I don't want to discuss here.

This article discusses several alternatives to bind list controls with various types of data sources, the main focus being the use of XML files. Although we will use ListBox as the example, you could easily extend the technique to other list controls inherited from the System.Web.UI.WebControls.ListControl class. They include CheckBoxList, DropDownList, and RadioButtonList.

Hardcoding Listbox

As a start, let's recall how we usually define a listbox in HTML. The following code shows the original tag to render a listbox. It is the most straightforward approach, raising the least overhead, but you don't have much flexibility to control the behavior of the listbox from your server script.

<select size="1" id="lstPizzaTopping">
  <option value="supreme">Supreme</option>
  <option value="italianclassic">Italian Classic</option>
  <option value="meatlover">Meat Lover</option>
</select>

In ASP.NET, you could use ListBox server control to produce the same result, but with more capabilities to control its behavior and properties.

<asp:listbox rows="1" id="lstPizzaTopping" runat="server">
  <asp:listitem value="supreme">Supreme</asp:listitem>
  <asp:listitem value="italianclassic">Italian Classic</asp:listitem>
  <asp:listitem value="meatlover">Meat Lover</asp:listitem>
</asp:listbox>

Let's have a little twist in the code. Instead of hardcoding items in the ListBox, you could programmatically add items to ListBox using ListItem object. The ListItem takes two parameters, the text and the value of the item. If you leave the second parameter unspecified, the value of an item is the same as its text. The following code shows how to do that:

<script runat="server">

Sub Page_Load(src as Object, e as EventArgs)

 lstPizzaTopping.Items.Add(new ListItem("Supreme", "supreme"))
 lstPizzaTopping.Items.Add(new ListItem("Italian Classic", "italianclassic"))
 lstPizzaTopping.Items.Add(new ListItem("Meat Lover", "meatlover"))

</script>

...
...

<asp:listbox rows="1" id="lstPizzaTopping" runat="server" />

Data Binding Listbox

In fact, ASP.NET allows you to bind the content of a ListBox with an object. The object could be an array, a collection object, a database or even an XML file. The following example shows how to bind a ListBox with an array of String. We will explore XML data binding in much detail later.

<script runat="server">

Sub Page_Load(src as Object, e as EventArgs)

  Dim arrPizzaTopping as String() = _ 
     { "Supreme", "Italian Classic", "Meat Lover" }

  lstPizzaTopping.DataSource = arrPizzaTopping
  lstPizzaTopping.DataBind()

End Sub

</script>

...
...

<asp:listbox rows="1" id="lstPizzaTopping" runat="server" />

What if we add a new element to the array? Will the ListBox reflect the result? It won't, unless you call the DataBind method again. So with this data binding technique, you have full control of when and where to update the ListBox.

Let's see another example of data binding using the new ArrayList object in ASP.NET. The ArrayList is similar to an array in classic VB term, but it has more functionality and can support more complex data types. The ArrayList object is actually a collection, so we treat one as a collection. To add a new item, we call the method Add and supply the object to Add, in this case it is a string.

<script runat="server">

Sub Page_Load(src as Object, e as EventArgs)

  Dim arrPizzaTopping as new ArrayList()
  arrPizzaTopping.Add("Supreme")
  arrPizzaTopping.Add("Italian Classic")
  arrPizzaTopping.Add("Meat Lover")
  lstPizzaTopping.DataSource = arrPizzaTopping
  lstPizzaTopping.DataBind()

End Sub

</script>

...
...

<asp:listbox rows="1" id="lstPizzaTopping" runat="server" />

Data binding is a great example of separating the user interface (e.g.. the HTML codes) with the scripts. But with data binding techniques mentioned above, we are still bounded with the static data that should be hard coded into our aspx file. What if the data is dynamic? And what if we want to reuse the ListBox in other pages? For cases like this, we need to rely on an external data source for the ListBox. Typically, we use a database and store the ListBox content in a table. Many articles already discussed this technique. For example, you could refer to Scott Mitchell's article for a discussion about data binding a list control with Access database.

Enough with databases, now we would like to try a new alternative using an XML file. An XML file is a plain text file, so you could easily create and edit the file using Notepad. The following code block is an example of an XML file that contains data for the ListBox. It has two parts, clearly marked by the commentary tags. The first part contains a list of "pizza toppings", and the latter contains a list of "pizza crust". Each part has several entries, and in each entry there is <value> and <desc> elements that hold the item value and item description respectively. Remember that this XML file is just an example. You could define your own element and content. But if you happen to be hungry, don't blame me. Anyway, pizza and programming are a great match!

<?xml version="1.0" standalone="yes" ?>
<lookup>
<!--<span class="code-comment"> START OF: Topping --></span>
  <topping>
    <value>supreme</value>
    <desc>Supreme</desc>
  </topping>
  <topping>
    <value>italianclassic</value>
    <desc>Italian Classic</desc>
  </topping>
  <topping>
    <value>meatlover</value>
    <desc>Meat Lover</desc>
  </topping>
<!--<span class="code-comment"> END OF: Topping --></span>

<!--<span class="code-comment"> START OF: Crust --></span>
  <crust>
    <value>original</value>
    <desc>Original Crust</desc>
  </crust>
  <crust>
    <value>handstretched</value>
    <desc>Hand-Stretched Crust</desc>
  </crust>
  <crust>
    <value>pan</value>
    <desc>Pan Crust</desc>
  </crust>
<!--<span class="code-comment"> END OF: Crust --></span>
</lookup>

Now comes the magic. There is nothing special with the XML file, unless you load it into ADO.NET's DataSet. ADO.NET strongly supports XML that it can construct a relational-information based on an XML file. For instance, supplied with the XML file mentioned before, ADO.NET will automatically create a DataSet named lookup that contains two tables, topping and crust. Table topping has two columns, value and desc and has three rows. Similarly, table crust has value and desc columns and three rows. How ADO.NET reads and constructs those tables is known as the schema inference. The following diagram visualizes the DataSet and its two DataTables.

To load an XML file into a DataSet, you use the following codes. The first line creates a new instance of a DataSet. The second line calls ReadXml method and passes the full file path of the XML file. We use Server.MapPath to convert virtual path of the file as recognized by IIS to the physical path.

Dim myDataSet as DataSet = New DataSet
myDataSet.ReadXml(Server.MapPath("lookup.xml"))

Binding tables to ListBox is simple. We just set the DataSource and DataMember properties of the ListBox to refer to the specific table and then call DataBind method. Don't forget to set the DataTextField and DataValueField properties to indicate which column is used as value and which one is used as text, since ASP.NET cannot determine it automatically!

<script runat="server">

Sub Page_Load(src as Object, e as EventArgs)

  ...
  ...
  lstPizzaTopping.DataSource = myDataSet
  lstPizzaTopping.DataMember = "topping"
  lstPizzaTopping.DataBind()

End Sub

</script>

...
...

<asp:listbox rows="1" 
             id="lstPizzaTopping"
             datatextfield="desc"
             datavaluefield="value"
             runat="server" />

Sorting Items in ListBox

Occasionally, you want to display items in a sorted order. The following code demonstrates this to Pizza Topping ListBox. The first line creates an instance of DataView as the default view of table topping and names it as myDataView. The second line sets the sort property to desc ASC, informing the data to be sorted on desc column in ascending way. Then in the next line, we set the DataSource property of the ListBox to myDataView and call the DataBind method to effectively render the content of the ListBox.

Dim myDataView as DataView = myDataSet.Tables("topping").DefaultView
myDataView.Sort = "desc ASC"
lstPizzaTopping.DataSource = myDataView
lstPizzaTopping.DataBind()

Performance issues

Since data binding is a resource intensive process, you would consider binding a list control only when you need to. You would data bind a list control if the content is dynamic or the list control is intentionally made reusable. The latter reason is when the same ListBox appears in many web pages. It really cuts time when you need to change the content of those ListBoxes because you don't need to modify every one of them. If none of the reasons suits you, hard code the content of list control to avoid unnecessary overhead.

Sorting items in ListBox also takes an amount of resources. If you want the ListBox to always appear sorted anywhere and anytime, consider writing the XML in a sorted order rather than sorting the ListBox programmatically every time you use it.

Conclusions

This articles walks you on various ways to produce list controls in your web pages. It starts from the straightforward hard coding technique, to data binding with array, ArrayList and finally XML that supports dynamic content. Data binding with XML is an alternative you may like to consider instead of database. It is relatively easy to implement and could avoid much overhead introduced by typical SQL database.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Enrico Elizar Samuel
Web Developer
Singapore Singapore
Currently, he is in Singapore doing a contract work for a multinational company. During weekend, he is busy exploring Singapore with his lovely fiance to find the best food.

Comments and Discussions

 
GeneralThank you! PinsussAnonymous30-Nov-04 8:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141022.1 | Last Updated 14 Aug 2002
Article Copyright 2002 by Enrico Elizar Samuel
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid