Learn to Use the New Data Source Controls in ASP.NET 2.0

here’s no shortage of useful, new controls to investigate in ASP.NET 2.0. In my last article, I discussed the new GridView and DetailsView controls. In that article I also discussed the use of the SqlDataSource control, which allows you to declaratively connect to a SQL data source without any coding.

Besides the SqlDataSource control, ASP.NET 2.0 comes with several other new data source controls:

  • AccessDataSource?connects to an Access database
  • ObjectDataSource?connects to a business object and treats it as a data source
  • DataSetDataSource?manipulates an XML document as a dataset
  • XmlDataSource?loads an XML document for binding to controls such as the DataList and TreeView controls
  • SiteMapDataSource?loads a site map file and exposes it to controls such as the TreeView and SiteMapPath controls

Figure 1 shows these new data source controls under the Data tab in the Toolbox.

Figure 1. In Control: The various data source controls are stored under the Data tab in the Toolbox.

In this article, I will concentrate on the ObjectDataSource control, DataSetDataSource control, and the XmlDataSource control. The SqlDataSource control is discussed in the previous article and the AccessDataSource control is similar to it, except that it connects to an Access database. That leaves the SiteMapDataSource control for discussion in a future article where I’ll use it to build navigation objects.

The ObjectDataSource Control
The ObjectDataSource control allows binding your business objects to data controls such as the DataGrid control. To see how the ObjectDataSource control works, create a new Web site project in Visual Studio 2005 Beta 1 and add a new class called Products to the project:

Imports Microsoft.VisualBasicImports System.DataImports System.Data.SqlClientPublic Class Products    Public Function getProducts() As DataSet        Dim conn As New SqlConnection("Server=(local);Integrated Security=True;Database=Northwind;Persist 
Security Info=True") Dim adapter As New SqlDataAdapter("SELECT [ProductID], [ProductName], [SupplierID], [CategoryID],
[QuantityPerUnit], [UnitPrice] FROM [Products]", conn) Dim ds As New DataSet adapter.Fill(ds, "Products") Return ds End FunctionEnd Class

The Products class contains a getProducts method that returns a dataset containing all the products in the Northwind database. Using the ObjectDataSource control, you can allow a data control to bind to this class. To do so, drag-and-drop an ObjectDataSource control onto the default page (see Figure 2).

Figure 4. Get Products: Choose a method to bind to the Select operation.

Click on the ‘Configure Data Source?’ link in the Smart Tag. You will see the window shown in Figure 3. Select the name of the business object?in this case it is the Products class?and click Next.

In the next window, you will select the method to use for each operation, such as Select, Update, Insert, and Delete. For this example, the Products class has only the getProducts method, so choose the getProducts method for the Select tab (see Figure 4) and click Finish.

Figure 6. Getting Wind of Northwind: The default .aspx page displays the records using the GridView control.

Next, drag-and-drop a GridView control to the page and bind it to ObjectDataSource1. Check the three options available in the Smart Tag?Enable Paging, Enable Scripting, and Enable Selection (see Figure 5).

That’s it! Press F5 to load the page. You will be able to see the records in the Products table in the Northwind database in the GridView control (see Figure 6).

What about editing rows in the table through the ObjectDataSource control? To do that, you need to have another method in the Products class to perform the editing work. So, add a new method called updateProducts to the Products class:

Public Sub updateProducts(ByVal ProductID As Integer, _                      ByVal ProductName As String, _                      ByVal SupplierID As Integer, _                      ByVal CategoryID As Integer, _                      ByVal QuantityPerUnit As String, _                      ByVal UnitPrice As Double)   Dim conn As New SqlConnection("Server=(local);Integrated Security=True;Database=Northwind;Persist Security Info=True")   Dim adapter As New SqlDataAdapter("SELECT * FROM Products WHERE ProductID=" & ProductID, conn)   Dim ds As New DataSet   adapter.Fill(ds, "Products")   With ds.Tables(0).Rows(0)       .Item("ProductName") = ProductName       .Item("SupplierID") = SupplierID       .Item("CategoryID") = CategoryID       .Item("QuantityPerUnit") = QuantityPerUnit       .Item("UnitPrice") = UnitPrice   End With   Dim cb As New SqlCommandBuilder(adapter)   adapter.Update(ds, "Products")End Sub

Now configure the ObjectDataSource control again. This time round, click on the Update tab, and select the updateProducts method. Then click Finish (see Figure 7).

In the Smart Tag of the GridView control, check the Enable Editing option (see Figure 8). Then, press F5 to load the page again. You can now edit the rows in the table (see Figure 9). For deletion, you can likewise create a new method to perform a deletion and then update the ObjectDataSource control again.

Figure 8. Add a Checkbox: Enable editing on the GridView control.
Figure 9. Aniseed Syrup? Edit a row in the GridView control.

The DataSetDataSource Control
The DataSetDataSource control allows you to manipulate an XML document just like a dataset. Suppose you have the following XML document (Books.xml) in your project:

      ASP.NET 2.0: A Developer's Notebook (O'Reilly)         December 2004    To bring you up to speed with ASP.NET 2.0, this practical book offers nearly 50 hands-on projects. 
Each one explores a new feature of the language, with emphasis on changes that can increase productivity, simplify
programming tasks, and help you add new functionality to your applications. You get the goods straight from the
masters in an informal, code-intensive style. Part of our new Developer's Notebook series.
.NET Compact Framework Pocket Guide (O'Reilly) May 2004 Looking to create applications for Pocket PC and Windows based Smartphones? The new .NET Compact
Framework Pocket Guide will teach you what you need to know. This handy reference provides a quick tour of the
.NET Compact Framework and includes several working projects to get you productive straightaway. Whether you're
new to mobile programming or new to Visual Studio .NET 2003, this pocket guide will get you started writing mobile
Windows XP Unwired (O'Reilly) August 2003 Windows XP Unwired provides a complete introduction to all the wireless technologies supported by
Windows XP, including Wi-Fi (802.11b, a, and g), infrared, Bluetooth, CDMA2000, and GPRS. It's a one-stop wireless
information source for technically savvy Windows XP users. This book will show you the full-spectrum view of
wireless capabilities of Windows XP, and how to take advantage of them.
Figure 11. All Set: Here’s the running .aspx page, which displays records from books.xml using the GridView control.

I will use the DataSetDataSource control to bind this XML document to the GridView control. Drag-and-drop a DataSetDataSource control onto the default page. Click on the ‘Configure Data Source?’ link in the Smart Tag (see Figure 10).

In the Configure Data Source window, enter “~/Books.xml” for the data file, and click OK. Drag-and-drop another GridView control to the page and bind it to DataSetDataSource1. Check the Enable Paging, Enable Sorting, and Enable Selection options.

Figure 14. Make a New Key: Specify a key in the schema file.

That’s it! Press F5 to load the page. The GridView control will display the information in the XML file (see Figure 11).

Using the GridView control, you can also enable the editing of the XML document through the following steps.

First, set the ReadOnly property of the DataSetDataSource control to False. This will allow the XML document to be modified. Next, enable Editing on the GridView control (see Figure 12). Set the DataKeyNames property of the GridView control to Title.

You also need to generate a schema for the XML document. You can do this in Visual Studio 2005 by double-clicking the XML document in Solution Explorer and then right-clicking on it and selecting Create Schema (see Figure 13).

Figure 15. Change Title: You can now edit the GridView control.

In the schema file that is created, right-click on the Title element (see Figure 14) and then select Add?>New key?. This will define the Title element as the key identifying the individual rows in the GridView control. Then check the dataset primary key checkbox and click OK.

Finally, configure the DataSetDataSource control by specifying the name of the schema file “~/.Books.xsd,” in the field under the Data file name. With that, the GridView control is editable (see Figure 15).

The XmlDataSource Control
Unlike the DataSetDataSource control, the XmlDataSource control is suitable for binding to XML documents that do not have a structure similar to that of a dataset. Consider the RSS document in Figure 16, saved as MSDN.xml in the project.

Figure 16. The RSS Document: The XMLDataSource control lets you manage poorly formed XML.
Figure 17. The Mighty DataList: Bind the DataList control to the XmlDataSource control.

Drag-and-drop an XmlDataSource control onto the page and click on the ‘Configure Data Source?’ link in the Smart Tag. In the Configure Data Source window, set the Data file as “~/MSDN.xml.” In the XPath Expression, set it as “rss/channel/item.” The purpose of the XPath expression is to set a filter for the XML document so that only a subset of the document is returned. Now drag-and-drop a DataList control onto the page and bind it to XmlDataSource1 (see Figure 17).

In the Smart Tag, choose ‘Auto Format?’ and select the Slate scheme. Now, switch to Source view and add the bold portion of the source code sample below:


RSS Feeds

That’s it! Press F5 to load the page. You will now be able to see the DataList control displaying a subset of the RSS document (see Figure 18). And you’ve just written an RSS reader without writing a single line of code!

Figure 18. An RSS Reader: Thanks to the XMLDataSource control you can build a dynamic RSS feed without any coding at all.

If you are feeling adventurous, try loading the RSS document dynamically at runtime, allowing the user to choose which news feed they want to see. To do that, add a TextBox and Button control to the page (see Figure 19).

To load the XML document dynamically, code the Load button as follows:

Sub btnLoad_Click(ByVal sender As Object, _                  ByVal e As System.EventArgs)    XmlDataSource1.DataFile = txtURL.TextEnd Sub

You can now change the news feed dynamically!

In this article, you have seen how to use the various data source controls in ASP.NET 2.0 to connect to various data sources (and not just databases). The data source controls can save you from writing tons of code for data access. You can now declaratively connect to your data sources.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a