| Main ASP .NET Tutorial Index |
Scott Mitchell June 2006 Download the ASPNET_Data_Tutorial_4_CS.exe sample code. Contents of Tutorial 4 (Visual C#)
Introduction IntroductionWith our application architecture and website
page layout complete, we're ready to start exploring
how to accomplish a variety of common data- and
reporting-related tasks. In the previous tutorials
we've seen how to programmatically bind data from
the DAL and BLL to a data Web control in an ASP.NET
page. This syntax – assigning the data Web control's
ASP.NET 2.0 ships with five built-in data source controls – SqlDataSource, AccessDataSource, ObjectDataSource, XmlDataSource, and SiteMapDataSource – although you can build your own custom data source controls, if needed. Since we have developed an architecture for our tutorial application, we'll be using the ObjectDataSource against our BLL classes.
Figure 1. ASP.NET 2.0 Includes Five Built-In Data Source Controls The ObjectDataSource serves as a proxy for
working with some other object. To configure the
ObjectDataSource we specify this underlying object
and how its methods map to the ObjectDataSource's
Figure 2. The ObjectDataSource Serves as a Proxy While the ObjectDataSource can be used to invoke methods for inserting, updating, or deleting data, let's just focus on returning data; future tutorials will explore using the ObjectDataSource and data Web controls that modify data. Step 1: Adding and Configuring the ObjectDataSource ControlStart by opening the Note Alternatively, you may first add the data Web control to the page and then, from its smart tag, choose the <New data source> option from the drop-down list. To specify the ObjectDataSource's underlying object and how that object's methods map to the ObjectDataSource's, click on the Configure Data Source link from the ObjectDataSource's smart tag.
Figure 3. Click the Configure Data Source Link from the Smart Tag This brings up the Configure Data Source wizard.
First, we must specify the object the
ObjectDataSource is to work with. If the "Show only
data components" checkbox is checked, the drop-down
list on this screen lists only those objects that
have been decorated with the From this first screen choose the
Figure 4. Specify the Object to Use with the ObjectDataSource Control The next screen in the wizard prompts you to
select what method the ObjectDataSource should
invoke. The drop-down lists those methods that
return data in the object selected from the previous
screen. Here we see
Figure 5. Choose the Method for Returning Data from the SELECT Tab Configure the ObjectDataSource ManuallyThe ObjectDataSource's Configure Data Source
wizard offers a quick way to specify the object it
uses and to associate what methods of the object are
invoked. You can, however, configure the
ObjectDataSource through its properties, either
through the Properties window or directly in the
declarative markup. Simply set the <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetProducts"
TypeName="ProductsBLL">
</asp:ObjectDataSource>
Even if you prefer the Configure Data Source wizard there may be times when you need to manually configure the ObjectDataSource, as the wizard only lists developer-created classes. If you want to bind the ObjectDataSource to a class in the .NET Framework – such as the Membership class, to access user account information, or the Directory class to work with file system information – you'll need to manually set the ObjectDataSource's properties. Step 2: Adding a Data Web Control and Binding it to the ObjectDataSourceOnce the ObjectDataSource has been added to the
page and configured, we're ready to add data Web
controls to the page to display the data returned by
the ObjectDataSource's Binding a GridView to the ObjectDataSourceAdd a GridView control from the Toolbox to
Figure 6. A GridView Has Been Added to the Page and Bound to the ObjectDataSource You can then customize, rearrange, or remove the GridView's BoundFields by clicking the Edit Columns option from the smart tag.
Figure 7. Manage the GridView's BoundFields Through the Edit Columns Dialog Box Take a moment to modify the GridView's
BoundFields, removing the <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="ObjectDataSource1" EnableViewState="False">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="SupplierName" HeaderText="Supplier" ReadOnly="True" SortExpression="SupplierName" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price"
HtmlEncode="False" SortExpression="UnitPrice">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
</Columns>
</asp:GridView>
Figure 8. The GridView's BoundFields Have Been Customized Using Themes for a Consistent LookThese tutorials strive to remove any
control-level style settings, instead using
cascading style sheets defined in an external file
whenever possible. The If we set these Our Theme won't include any images or CSS files
(we'll leave the stylesheet Start by adding a new Skin File to your project
named
Figure 9. Add a Skin File Named
Skin files need to be placed in a Theme, which
are located in the
Figure 10. Let Visual Studio
Create the This will create a new Theme in the
Figure 11. The GridView Theme
has Been Added to the Rename the GridView Theme to DataWebControls
(right-click on the GridView folder in the
This defines the default properties for the <asp:DetailsView runat="server" CssClass="DataWebControlStyle"> <AlternatingRowStyle CssClass="AlternatingRowStyle" /> <RowStyle CssClass="RowStyle" /> <FieldHeaderStyle CssClass="HeaderStyle" /> </asp:DetailsView> With our Theme defined, the last step is to apply
the Theme to our ASP.NET page. A Theme can be
applied on a page-by-page basis or for all pages in
a website. Let's use this theme for all pages in the
website. To accomplish this, add the following
markup to <pages styleSheetTheme="DataWebControls" /> That's all there is to it! The
Figure 12. The GridView Displays the Product's Name, Category, Supplier, Price, and Discontinued Information Displaying One Record at a Time in the DetailsViewThe GridView displays one row for each record
returned by the data source control to which it's
bound. There are times, however, when we may want to
display a sole record or just one record at a time.
The
DetailsView control offers this functionality,
rendering as an HTML Start by adding a DetailsView control above
the GridView in
Figure 13. Add a DetailsView to the Page and Bind it to the ObjectDataSource Like the GridView, the DetailsView's BoundFields
can be tweaked to provide a more customized display
of the data returned by the ObjectDataSource. Figure
14 shows the DetailsView after its BoundFields and
Figure 14. The DetailsView Shows a Single Record Note that the DetailsView only displays the first record returned by its data source. To allow the user to step through all of the records, one at a time, we must enable paging for the DetailsView. To do so, return to Visual Studio and check the Enable Paging checkbox in the DetailsView's smart tag.
Figure 15. Enable Paging in the DetailsView Control
Figure 16. With Paging Enabled, the DetailsView Allows the User to View Any of the Products We'll talk more about paging in future tutorials. A More Flexible Layout for Showing One Record at a TimeThe DetailsView is pretty rigid in how it
displays each record returned from the
ObjectDataSource. We may want a more flexible view
of the data. For example, rather than showing the
product's name, category, supplier, price, and
discontinued information each on a separate row, we
may want to show the product name and price in an
The FormView control provides this level of customization. Rather than using fields (like the GridView and DetailsView do), the FormView uses templates, which allow for a mix of Web controls, static HTML, and databinding syntax. If you are familiar with the Repeater control from ASP.NET 1.x, you can think of the FormView as the Repeater for showing a single record. Add a FormView control to the
Figure 17. The FormView Must
Include an You can bind the FormView directly to a data
source control through the FormView's smart tag,
which will create a default <asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource1" EnableViewState="False">
<ItemTemplate>
<h4><%# Eval("ProductName") %> (<%# Eval("UnitPrice", "{0:c}") %>)</h4>
Category: <%# Eval("CategoryName") %>; Supplier: <%# Eval("SupplierName") %>
</ItemTemplate>
</asp:FormView>
Figure 18. The First Product (Chai) is Displayed in a Custom Format The Like the DetailsView, the FormView only shows the first record returned from the ObjectDataSource. You can enable paging in the FormView to allow visitors to step through the products one at a time. SummaryAccessing and displaying data from a Business Logic Layer can be accomplished without writing a line of code thanks to ASP.NET 2.0's ObjectDataSource control. The ObjectDataSource invokes a specified method of a class and returns the results. These results can be displayed in a data Web control that's bound to the ObjectDataSource. In this tutorial we looked at binding the GridView, DetailsView, and FormView controls to the ObjectDataSource. So far we've only seen how to use the
ObjectDataSource to invoke a parameter-less method,
but what if we want to invoke a method that expects
input parameters, such as the Happy Programming! Further ReadingFor more information on the topics discussed in this tutorial, refer to the following resources:
About the Author
Scott Mitchell, author of six ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, and writer, recently completing his latest book, Sams Teach Yourself ASP.NET 2.0 in 24 Hours. He can be reached at mitchell@4guysfromrolla.com or via his blog, which can be found at http://ScottOnWriting.NET. Special Thanks To...This tutorial series was reviewed by many helpful reviewers. Lead reviewer for this tutorial was Hilton Giesenow. Interested in reviewing my upcoming MSDN articles? If so, drop me a line at mitchell@4GuysFromRolla.com. |
||||


















