Manipulating data 32 in asp.net 2.0: Nesting of data controls _ self-study process

Source: Internet
Author: User
Tags eval instance method

Introduction

In addition to static HTML and data-binding syntax, template can also contain Web controls and user controls. The properties of these controls can be set by declaring syntax, data-binding syntax, or programmatically using event handling on the server side.

By embedding controls in template, you can customize the interface to enhance the user experience. For example, in the GridView control, use the TemplateField, We learned how to represent an employee's hire date by adding a Calendar control to the TemplateField of the GridView. In adding validation controls to the edit and add interfaces and customizing the data modification interface, we learned how to add validation controls, TextBox, DropDownList and other Web controls come from defining edits, inserting interfaces.

Template can also contain other data controls. That is, we can allow DataList to include other DataList (or Repeater,gridview,detailsview, etc.) in template. The challenge for this job is to bind data to the data controls inside. There are several different ways to do this, including from the declarative language using ObjectDataSource to direct programming.

In this chapter we will explore how to use nested repeater. The outer repeater display each category as an item, Contains the name and description of category. The repeater in each category item shows each product under this category (see Figure 1). We will learn how to create inner-layer repeater by declaring and programming them separately.


figure 1:category and belong to its product are listed together

First step: Create a Category List

When you create a page that uses nested data controls, I find it very helpful to start with the design, creation, and testing of the outermost controls, and this time without the controls nested inside the tube. Therefore, We first implement adding a repeater to the page to list category name and description.

Open the Nestedcontrols.aspx page in the Datalistrepeaterbasics folder. Add a Repeater control, set the ID to categorylist ... With its smart tag, choose to create a new ObjectDataSource named Categoriesdatasource.


Figure 2: Creating a ObjectDataSource named Categoriesdatasource

Configure O with the GetCategories method of the Categoriesbll class


Figure 3: Configuring the GetCategories method with the Categoriesbll class ObjectDataSource

We need to switch to the source view to manually enter the declaration code to specify the template content of the repeater. Add a ItemTemplate with a

<asp:repeater id= "CategoryList" datasourceid= "Categoriesdatasource" enableviewstate= "
 False" runat= "Server" >
 <ItemTemplate>
   
 

Figure 4 shows that the page is now browsed in the browser.


Figure 4: Listing the Name and description of each category, separated by horizontal lines

Step two: Increase the nested repeater display product

Our next task is to add a repeater to the ItemTemplate of categorylist to display the product that belongs to each category. There are many ways to access the repeater data in the inner layer, We're going to explore two kinds of now we're creating product in the ItemTemplate of CategoryList repeater. Repeater. Each product will contain name and price we add the following tag to the ItemTemplate in CategoryList:

<asp:repeater id= "productsbycategorylist" enableviewstate= "False"
 runat= "Server" >
 < headertemplate>
  <ul>
 </HeaderTemplate>
 <ItemTemplate>
  <li>< strong><%# eval ("ProductName")%></strong>
   (<%# eval ("UnitPrice", "{0:c}")%>) </li>
 </ItemTemplate>
 <FooterTemplate>
  </ul>
 </FooterTemplate>
</ Asp:repeater>

Step three: Bind the product under each category to Productsbycategorylist Repeater

If you look at the page now, you'll see a page like Figure 4 because we haven't bound any data in the repeater. There are several ways to bind an appropriate product record to a repeater. Some of them will be more effective. The main task now is to get the right product for the specified category. You can bind data to an inner repeater by ObjectDataSource the syntax in ItemTemplate or by programming directly in the background code.

Access to data through ObjectDataSource and ItemDataBound

Here we still use ObjectDataSource to achieve. Productsbll class of Getproductsbycategoryid (Category)
method to return the products information for a specific CategoryID. Therefore, we will create a new ObjectDataSource in the ItemTemplate of CategoryList repeater and configure it with this method. Unfortunately, Repeater does not allow you to modify the template through Design view, so we need to add the declaration syntax manually. See the following code:

  
 

When using the ObjectDataSource method we need to set the DataSourceID of Productsbycategorylist repeater to ObjectDataSource ( Productsbycategorydatasource). Note that ObjectDataSource has a <asp:Parameter> to specify the pass to Getproductsbycategoryid ( CategoryID) CategoryID. But how do we specify this value? We can set the DefaultValue property to <asp:parameter> see the following code:

<asp:parameter name= "CategoryID" Type= "Int32" defaultvalue=
  ' <%# Eval ("CategoryID") '/>

Unfortunately, data-binding syntax can only be used in controls that have databinding events. The parameter class does not have such an event, so using it can be an error. We need to categorylist Repeater's ItemDataBound creates an event handler to set this value. The ItemDataBound event is fired when each item is bound to a repeater. So every time the outer repeater fires this time, We can pass the current Caegoryid value to the CategoryID parameter of the Productsbycategorydatasource ObjectDataSource. The following code is for CategoryList Repeater's ItemDataBound creates an event handler:

 protected void Categorylist_itemdatabound (object sender, RepeaterItemEventArgs e) {i
  F (e.item.itemtype = = ListItemType.AlternatingItem | | E.item.itemtype = = ListItemType.Item) {//Reference the Categoriesrow object being bound to this RepeaterItem Ind. Categoriesrow category = (Northwind.categoriesrow) ((System.Data.DataRowView) e.item.dataitem).
  Row; Reference the Productsbycategorydatasource objectdatasource objectdatasource Productsbycategorydatasource = (Objec
  Tdatasource) E.item.findcontrol ("Productsbycategorydatasource"); Set the CategoryID Parameter value productsbycategorydatasource.selectparameters["CategoryID"]. DefaultValue = category.
 Categoryid.tostring (); } 
       

This event handler first guaranteed that we were working with the data item instead of the Header,footer or separator item. Then, reference the Categoriesrow instance that was just bound to the current repeateritem. Finally, Refers to the ObjectDataSource in ItemTemplate and passes the CategoryID of the current RepeaterItem to the CategoryID parameter.

In this event handler, the Productsbycategorylist repeater in each repeateritem is bound to the product in RepeaterItem category. See Figure 5.


Figure 5: The outer repeater lists each category; The repeater in the inner layer lists the products that belong to category

Direct programming to get products under category

In addition to using ObjectDataSource to get the PROUDCT under the current category, we can also be in the code-behind of the ASP.net page (or in the App_Code folder or in a separate class project) To create a method that returns the appropriate product set based on the incoming CategoryID. Suppose there is a getproductsincategory (CategoryID) in the code-behind of the ASP.net page. Method. We can use this method to bind the product under the current category to the repeater in the inner layer. See the following code:

<asp:repeater runat= "Server" id= "productsbycategorylist" enableviewstate= "False"
  datasource= ' <%# Getproductsincategory ((int) (Eval ("CategoryID"))%> ' > ...
</asp:Repeater>

The DataSource property of repeater specifies that its data is obtained through Getproductsincategory (CategoryID) by binding syntax. Because eval ("Categryid") returns an object type, We convert it into an integer before it passes into Getproductsincategory (CategoryID). Note that the CategoryID here is through the outer repeater (CategoryList) of CategoryID ( Already bound to Categories table. Therefore it cannot be a null value. So we didn't check before binding.

We now need to create the Getproductsincategory (CategoryID) method. Simply use the Getproductsbycategoryid (CategoryID) of the PRODUCTSBLL class here method to return the productsdatatable on it. We created Getproductsincategory (CategoryID) in the Code-behind of the Nestedcontrols.aspx page. See the following code:

protected northwind.productsdatatable getproductsincategory (int categoryid)
{
 //Create An instance of the PRODUCTSBLL class
 Productsbll productapi = new Productsbll ();
 Return to the products of the category return
 Productapi.getproductsbycategoryid (CategoryID);
}

This method simply creates a PRODUCTSBLL instance and returns the return value of the Getproductsbycategoryid (CategoryID) method. Note that this method must be marked public or protected. If marked private Asp. NET page will not be invoked in the declaration tag.
After you have done this, browse the page in the browser. The page should look similar to using the ObjectDataSource and ItemDataBound event handler (Figure 5).

  Note: Creating the Getproductsincategory (CategoryID) method in the Code-behind of the ASP.net page seems to be just a form, After all, this method simply calls the method in the BLL. Why not directly call this method directly in the binding syntax in the inner layer repeater. Like what:
Datasource= ' <% #ProductsBLL. Getproductsbycategoryid (CType (Eval ("CategoryID"), Integer)%> ')
Although this declaration does not work (since the Getproductsbycategoryid (CategoryID) method is an instance method), You can modify the PRODUCTSBLL to include one of these static methods. Such modifications can meet the needs of the Getproductsincategory (CategoryID) method of the ASP.net page, But writing in Code-behind can be more flexible to get the data, which we'll see later.

Get all the product information

The first two methods we call the Getproductsbycategoryid (CategoryID) method of the Productsbll class to get the product of the current category (one through ObjectDataSource, The second way is through Getproductsincategory (CategoryID). Each time a method is invoked, the BLL call Dal,dal returns a specific record through the SQL query database.

If there are n category, this method accesses the database n+1 times-Returns all category,n times at a time to return the product under a specific category. However, we can access the database two times to get all the data we need-once to return all the category and returns all the product at once. Once we get all the product, we can filter it according to CategoryID and then bind it.

We simply need to modify the Getproductsincategory (CategoryID) method in the ASP.net page code-behind to achieve this function. We first return all of the product, Then filter according to the incoming CategoryID.

Private northwind.productsdatatable allproducts = null;
protected northwind.productsdatatable getproductsincategory (int categoryid)
{
 //I, if we ' ve yet to have Accessed all of the product information
 if (allproducts = null)
 {
  Productsbll productapi = new PRODUCTSBLL ();
  allproducts = Productapi.getproducts ();
 }
 Return the filtered view
 AllProducts.DefaultView.RowFilter = "CategoryID =" + CategoryID;
 return allproducts;
}

Note the allproducts variable. It returns all product information when the first call to Getproductsincategory (CategoryID) is made. Determines that after the Allproducts object is created, Filter the DataTable according to the CategoryID. This method reduces the number of accesses to the database from n+1 to 2 times.
This improvement does not modify the declaration language of the page. It only reduces the number of accesses to the database.

  Note: It may be taken for granted that reducing the number of database accesses can improve performance. But this is not necessarily. If you have a large number of CategoryID-null product, a part of the product returned using the GetProducts method will not be displayed. And if you only need to display a portion of the category PROUDCT (this is true when paging), and return all of the product, which is a waste of resources. Typically, performance analysis is performed on two techniques, and the only correct approach is to set up common scenarios for stress testing.

Summarize

In this chapter we learned how to nest Web controls. Show each category by how to repeater the outer layer The inner layer repeater displays the product under each category as an example. The main task is to get the correct data and bind it to the inner-layer Web controls. There are many ways to use it, Here we discuss two kinds. The first is to bind to the inner control using the ItemTemplate of the outer-layer control. The second is to use the Code-behind method in the ASP.net page. It is bound by the DataSource property of the inner control. The control used in this chapter The pieces are repeater, or you can nest repeater in the GridView, or the GridView nested in DataList.

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.

Related Article

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.