Using the XmlDataSource Data property for easy samples

Here's a little trick to write samples that involves data binding controls to a database. It's very inconvenient to have to package a sample database with your code (especially when it's just a few lines of code in a blog), and just making sure your users have SQL Server installed is no small thing. All this just diverts the attention from what really matters: your sample code.

It's a little-known feature that XmlDataSource enables you to declaratively expose sample data to the page. Here's how it's done:

<asp:XmlDataSource runat="server" ID="data">
            <color name="Red" value="#FF0000"/>
            <color name="Green" value="#00FF00"/>
            <color name="Blue" value="#0000FF"/>
            <color name="Cyan" value="#00FFFF"/>
            <color name="Purple" value="#FF00FF"/>
            <color name="Yellow" value="#FFFF00"/>
<asp:DataList runat="server" ID="Repeat" DataSourceID="data" DataMember="color">
        <asp:Label runat="server" ID="ColorLabel" Text='<%# Eval("name") %>' />

The Data property of the datasource can contain an arbitrary XML document. You can define pseudo-tables in there (like the color pseudo-table in this example) just by adding elements with the same name under the root of the document. The columns are defined by the attributes.

As far as the data controls that consume the datasource are concerned, the XmlDataSource behaves exactly like a database and all you need to run the sample is the code.

Hope this helps.


Comments have been disabled for this content.