Working with data four in asp.net 2.0: Using ObjectDataSource to present data _ self-study process

Source: Internet
Author: User

Once the application architecture and page design have been completed, we can begin to explore how to implement a wide variety of common data to report presentation tasks. We have already learned how to bind data from the data access layer and business logic layer to the data controls on the ASP.net page. In a asp.net 1.x application, you can continue to use the data display in a asp.net 2.0 application by assigning a value to the DataSource property of the data control and then invoking the control's DataBind () method to achieve the presentation. However, the data source controls in ASP.net 2.0 provide a new way of using these controls to make it easy for you to bind data from the business logic layer that you created earlier, even without writing a line of code.

ASP.net 2.0 provides five built-in data source controls: SqlDataSource, AccessDataSource, ObjectDataSource, XmlDataSource, and SiteMapDataSource. Although you can also build your own custom data source control if you need it (custom controls). Now that we have completed the system architecture of the application example in the previous article, we will use ObjectDataSource based on the existing business logic classes.

Figure 1:asp.net 2.0 includes five types of built-in data source controls

ObjectDataSource acts as a proxy for other objects. By configuring ObjectDataSource, we specify these underlying objects and how the methods of these objects map to the ObjectDataSource Select, Insert, update, and delete methods. Once the underlying object is specified and its methods are mapped to the ObjectDataSource method, we can bind the ObjectDataSource to the data Web server control on the page. Asp. NET provides a number of data Web server controls, including GridView, DetailsView, RadioButtonList, and DropDownList, among others. In the life cycle of a page, the data Web server control may need to access the information it binds to, which is implemented by invoking the ObjectDataSource Select method, and if the data Web server control also supports inserts, updates, or deletes, Then the ObjectDataSource insert, update, or Delete method is invoked. These calls are sent via ObjectDataSource to the appropriate underlying object's methods, as shown in the following illustration.

Figure 2:objectdatasource acts as an agent

Although ObjectDataSource is used to insert, update, or delete data, we focus on returning data for the time being, and later chapters discuss data modification using the ObjectDataSource and Web server controls.

Step One: Add and configure the ObjectDataSource control

First, open the Simpledisplay.aspx page in the Basicreporting folder, switch to Design view, and drag a ObjectDataSource control from the toolbox to the page. It appears as a gray square in the design interface because it does not produce any declarative markup; it simply accesses the data by invoking the method of the object being made. The data returned through ObjectDataSource can be presented to the database Web server controls, such as the GridView, DetailsView, FormView, and so on.

Note: As an alternative, you can also add a data Web server control to the page, and then "show Smart Tags" and select "New Data Source ..." From the Select data source Drop-down box. Enter the DataSource Configuration Wizard to add a ObjectDataSource.

In order to specify the underlying object of the ObjectDataSource and to map the object's methods to the ObjectDataSource method, you can enter the data Source Configuration Wizard by clicking the "Configure Data source" link in the ObjectDataSource smart tag.

Figure 3: Clicking the "Configure Data source" link in the smart tag

This will go to the Data Source Configuration Wizard. First, we need to specify a business object for ObjectDataSource. If you check "Show data components only", the dropdown box shows only those objects that have been decorated with the [DataObject] feature. The current list should contain a typed dataset table adapter object (TableAdapters) and the business object that we have created in the previous article. If you forget to add [DataObject] features to your business logic classes, you won't see them in the current list. In that case, you can also see all objects without selecting "Show data Components only" to include the business objects (along with other classes in the typed DataSet –datatables, DataRows, and so on)

Select the business object PRODUCTSBLL from the Drop-down list in the first screen and click Next.

Figure 4: Specifying the business object used by the ObjectDataSource control

In the next Screen wizard you have the option to ObjectDataSource the method you want to invoke. The method in the Drop-down list is obtained from the business object selected in the previous screen. Here we can see the Getproductsbyproductid,getproducts,getproductsbycategoryid and Getproductsbysupplierid methods. Select Method GetProducts from the Drop-down list and click Finish (if you have added the [DataObjectMethod] feature to the PRODUCTBLL method as shown earlier, the item will be selected by default).

Figure 5: Selecting a method to return data from the Select tab

Manually configured ObjectDataSource

The ObjectDataSource Configuration Wizard provides a quick way to specify the objects it uses and to associate the methods that need to be invoked. However, you can also configure ObjectDataSource by its properties, either through the property window or directly in the declaration tag. Simply set the TypeName property to the name of the business object that is used, and set the SelectMethod property to the name of the method that needs to be invoked when the data is extracted.

 <asp:objectdatasource id= "ObjectDataSource1" runat= "selectmethod=" getproducts "typename="

  PRODUCTSBLL ">

</asp:ObjectDataSource>

Although you may prefer the Data Source Configuration Wizard, you sometimes need to manually configure ObjectDataSource because the Configuration Wizard lists only the classes that have been developed. If you want to bind ObjectDataSource to classes in the. NET framework-for example, membership class to access login user information, or directory class to manage file system information, Then you need to manually set the ObjectDataSource properties.

Step Two: Add a Data Web server control and bind it to the ObjectDataSource

After ObjectDataSource is added to the page and the configuration is complete, we can add a data Web server control to the page to show what is returned through the ObjectDataSource Select method. All data Web server controls can be bound to ObjectDataSource; Let's look at how to present ObjectDataSource data to the GridView, DetailsView, and FormView.

Bind a GridView to ObjectDataSource

Add a GridView control from the Toolbox to the page simpledisplay.aspx design interface. From the smart tag of the GridView, select the ObjectDataSource control that we added in the first step as the data source. This automatically generates a bound column (BoundField) in the GridView control based on each property of the data returned by the ObjectDataSource Select method (that is, the attributes defined by the typed dataset products).

Figure 6: Adding a GridView control to the page and binding to ObjectDataSource

Figure 7: Managing bound columns for the GridView control by editing the Column dialog box

  Spend some time modifying the bound columns of the GridView control, removing ProductID, SupplierID, CategoryID, QuantityPerUnit, UnitsInStock, UnitsOnOrder, and ReorderLevel these columns. The operation is simple, select the columns from the lower left list and click the Delete button (Red Cross) to remove them. Then, rearrange them, select the CategoryName and suppliername two bound columns and click the UP arrow button to release them before the UnitPrice column. Set the HeaderText properties of the remaining bound columns for products, Category, supplier, and price, respectively. Format Price is then listed as currency – Set the HTMLEncode property of the bound column to false and set the DataFormatString property to {0:c}. Finally, the Itemstyle/horizontalalign property sets the horizontal right-aligned of the bound column price and the checkbox column discontinued horizontally.

<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" 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 Horizo ntalalign= "right"/> </asp:BoundField> <asp:checkboxfield datafield= "discontinued" headertext= "Disconti" Nued "sortexpression=" discontinued "> <itemstyle horizontalalign=" Center "/> </asp:CheckBoxField> & Lt;/columns> </asp:GridView>

Figure 8:gridview Control Binding column Customization complete

Use Themes (Themes) to keep the display style consistent

This will remove the control-level style settings as much as possible, instead of using cascading style sheets defined in an external file. File Styles.css contains Datawebcontrolstyle, HeaderStyle, RowStyle, and AlternatingRowStyle These CSS styles can be used to indicate the appearance of the data Web server control. To achieve this, we can set the CssClass property of the GridView control to Datawebcontrolstyle,headerstyle, RowStyle, and AlternatingRowStyle's CssClass properties are also set similarly.

If we set these CssClass properties to a Web control, then we have to remember to explicitly record the value of each attribute and each data Web server control in our manual. A more convenient way to manage is to use a theme to define the association between CSS styles and the properties of the GridView, DetailsView, and FormView controls. Theme is a collection of property settings, pictures, and CSS styles at the control level that can be applied to all pages of the entire site to enforce constraints on appearance and perception.

Our theme will not include pictures and CSS files (we will leave the stylesheet Styles.css file as usual in the root directory of the Web application), but it will contain two skins (Skin). A skin is a file that contains the default property settings for a Web control. In particular, we will create a skin file that defines the appearance of the GridView and DetailsView, indicating the default CssClass associated properties.

Select the current project in Solution Explorer, choose Add New Item from the right-click menu, add a skin file to your item and name it Gridview.skin.

Figure 9: Add a skin file and name it Gridview.skin

Skin files need to is placed in a Theme, which are located in the App_Themes folder. Since we don ' t yet have such a folder, Visual Studio'll kindly offer to create one for the US when adding our A-Skin. Click Yes to create the App_theme folder and place the new Gridview.skin file there.

The skin file needs to be placed in a topic, and the subject file is stored in the App_Themes folder. Because we don't currently have this folder, Visual Studio will kindly propose creating one for us when we add the first skin file. Click "Yes" to automatically create the App_theme folder and place the Gridview.skin file you just added there.

Figure 10: Let Visual Studio create the App_theme folder automatically

This automatically creates a theme in the App_Themes folder, the subject name is GridView and contains the skin file Gridview.skin.

Figure 11: The subject GridView has been added to the App_theme folder

Rename the subject GridView to DataWebControls (choose Rename from the right menu of the GridView folder). Then, enter the tag of the Gridview.skin file as seen below:

<asp:gridview runat= "Server" cssclass= "Datawebcontrolstyle" >

 <alternatingrowstyle cssclass= " AlternatingRowStyle "/>

 <rowstyle cssclass=" RowStyle "/>  
 

The last part about our theme setting is to apply the theme to our ASP.net page. A theme can be applied to pages on one page, or to all pages under one site. Let's apply the theme to all the pages under the site. To achieve this, add the following tag to the <system.web> fragment of web.config:

<pages stylesheettheme= "DataWebControls"/>

It's done! Properties that are preset in the theme style sheet will not overwrite properties that are set directly at the control level. If you want the settings in the theme to be higher than the control's settings, you need to use the theme features in the subject style; Unfortunately, the settings for the theme feature do not appear in the logical view of visual Studio. Check asp.net Themes and skins Overview and server-side Using Styles to get more information about themes and skins; see how Themes to:apply asp.net get More information on how to configure the page to use a topic.

Figure 12:the GridView Display Product ' s Name, Category, Supplier, Price, and discontinued information

Display one piece of data at a time in a DetailsView control

In the GridView control, the data returned from the bound data source control is displayed as a single row. Sometimes, however, we just need to display a single record, or only one record at a time. The DetailsView control provides this functionality, which behaves as a <table> of two columns of HTML, and each row displays a field or a property. You can imagine DetailsView is only one piece of data the GridView flips 90 degrees.

First, add a DetailsView control above the GridView control in the page simpledisplay.aspx. Then, bind it to the same OBJECTDATASOURC control of the GridView. As with the GridView control, it generates a bound column for each property based on the data returned by the ObjectDataSource Select method. The only difference is that the bound columns of the DetailsView are arranged horizontally.

Figure 13: Add a DetailsView control to the page and bind to the ObjectDataSource

Binding columns similar to Gridview,detailsview can also be adjusted to provide some user-delivered displays. Figure 14 shows an example of a DetailsView control that makes the binding column and the CssClass property look similar to the GridView after it has been set.

Figure 14:detailsview control displays a record

Note The DetailsView control displays only the first record in its data source. In order for the user to be able to browse all records, we must allow DetailsView paging. To achieve this, go back to visual Studio and check "Enable paging" in the DetailsView smart tag.

Figure 15: Allow DetailsView control paging

Figure 16: When paging is enabled, the DetailsView control allows the user to view any one of the products

Later in the tutorial we will discuss the paging in detail.

A more flexible layout used to display a single record at a time

Using DetailView to show that every piece of data returned by ObjectDataSource seems a bit stiff. We may need more flexible data presentation. For example, on every single line, on the basis of displaying product ' s name, category, supplier, price, and discontinued information, we may need product name and The Price two column displays

The FormView control provides customization of the user at this level. On the basis of using fields (like the GridView and DetailsView), FormView controls use templates, which allows us to mix Web server controls, static HTML, and binding syntax (databinding syntax). If you are familiar with the repeater control in ASP.net 1.x, you can assume that FormView is a repeater that displays only one record.

Add a FormView control to the design interface of the page simpledisplay.aspx. The first Fromview control is displayed as a gray square and tells us that we need to edit the template content and we need to use ItemTemplate.

Figure 17:formview must contain a ItemTemplate

You can bind a data source control directly to it through the FormView smart tag, which automatically creates a default ItemTemplate (if ObjectDataSource sets InsertMethod and UpdateMethod, EditItemTemplate and InsertItemTemplate are also automatically created at the same time. However, here's an example where we will manually bind FormView and set its ItemTemplate. First, set the FormView DataSourceID property to ObjectDataSource Id:objectdatasource1, and then, create ItemTemplate, display product ' s in a

 <asp:formview id= "FormView1" runat= "Server" datasourceid= "ObjectDataSource1" enableviewstate= "False" >

 <ItemTemplate>

   
 

Figure 18: The first product (Chai) is displayed as a predefined format

<%# Eval (PropertyName)%> is the binding syntax. Method eval Returns the value of the specified property of the object bound to FormView. Check out Alex Homer's article simplified and Extended data Binding Syntax in asp.net 2.0 to get more details about databinding.

Like DetailsView, FormView displays the first record returned by ObjectDataSource. You can enable the FormView paging feature so that visitors can view each product in turn.

Summarize

Depending on the ObjectDataSource control of ASP.net 2.0, we can easily get and present data from the business logic layer without having to write a line of code. Ojbectdatasource invokes the method of the specified class and returns the result. These results can be presented in a data Web server control that is bound to ObjectDataSource. In this chapter we looked at how to bind to the GridView, DetailsView, and FormView controls to ObjectDataSource.

So far we've only looked at how to use Ojbectdatasource to invoke a method without parameters, but if we want to call a method that needs to pass in multiple parameters, such as the Getproductsbycategoryid in the class PRODUCTBLL ( CategoryID) method? In order to invoke a method that requires passing in one or more parameters, we need to configure ObjectDataSource to specify the values of these parameters. In the next chapter we'll look at how to do that.

I wish you a happy programming!

Author Introduction

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog Http://ScottOnWriting.NET.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.