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

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
applications.
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:

                 <%#XPath("title")%>
<%#XPath("pubDate")%>
<%#XPath("description")%>
Link

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.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,