Operating data 34 in asp.net 2.0: Master/From Report-Self-learning process based on DataList and repeater cross-page

Source: Internet
Author: User
Tags eval

Introduction

In the previous chapter we learned how to display master/slave information in a single page. Another pattern that is often used is to display the master-slave information separately in two pages. master/slave reports in front of the cross page We use this pattern by displaying all the supplier in the GridView. The GridView contains a HyperLinkField, links to another page, and pass the SupplierID through QueryString. The second page uses the GridView to list the product provided by the selected supplier.

Such a two-page master/ The table can also be implemented with DataList and repeater. The only difference is that DataList and Repeater do not provide hyperlinkfield. So we need to add a hyperlink control or use HTML in the ItemTemplate <a>. Hyperlink NavigateUrl attributes and the href properties of <a> can be defined by declaration or programming.

In this chapter we will explore the use of Repeater to list categories. Each list Item contains the name and description of category. You can link to the second page directly by name. On the second page, the PROUDCT provided by the selected Categroy is displayed with the DataList.

First Step: List categories

The first step in creating a master-detail table is to display the master record. Therefore, we first display categories in the main page. Open the Categorylistmaster.aspx page in the Datalistrepeaterfiltering folder, Add a repeater and then add a ObjectDataSource through the smart tag. Configure it using the GetCategories method of the Categriesbll class. See Figure 1.


Figure 1: Configuring the GetCategories method using the Categoriesbll class ObjectDataSource

We don't care how to add link first. Configures the repeater template to display the name and description of each category. See the following code:

<asp:repeater id= "Repeater1" runat= "Server" datasourceid= "ObjectDataSource1"
 enableviewstate= "False" >
 <HeaderTemplate>
 <ul>
 </HeaderTemplate>
 
 <ItemTemplate>
 <li> <%# eval ("CategoryName")%>-<%# eval ("Description")%></li>
 </ItemTemplate>
 
 < footertemplate>
 </ul>
 </FooterTemplate>
</asp:Repeater>
 
<asp:o Bjectdatasource id= "ObjectDataSource1" runat= "Server"
 oldvaluesparameterformatstring= "original_{0}"
 Selectmethod= "GetCategories" typename= "CATEGORIESBLL" >
</asp:ObjectDataSource>

After completing the above code, browse the page in the browser, as shown in Figure 2.


Figure 2: Listing all the Category

Step two: Convert category Name to link to the details Page

We are now going to add a link, and when the user clicks, it will link to the second page (productsforcategorydetails.aspx), where the "from" is displayed on the page. Information. This page displays the selected category product with DataList. In order to determine which category link was ordered, We need to upload CategoryID to the second page. The most direct way is through querystring. We pass this to productsforcategorydetails.aspx through the QueryString field named CategoryID. , view the Product,categoryid under Beverages Categroy as 1. Will the user visit productsforcategorydetails.aspx? Categoryid=1 page.

In order to create hyperlink we need to add hyperlink controls or add Html<a> to ItemTemplate; both methods are sufficient for each row's hyperlink. I prefer to use it for repeater. <a>. See the following code:

<li>
 <a href= ' productsforcategorydetails.aspx? categoryid=<%# eval ("CategoryID")%> ' >
 <%# eval ("CategoryName")%>
 </a>-<%# eval (" Description ")%>
</li>

Note that CategoryID can be written directly through the href attribute. Note Quotes and ellipses.

<li>
 <asp:hyperlink runat= "server" text= ' <%# Eval ("CategoryName")%> ' navigateurl= ' <%# '
 Productsforcategorydetails.aspx? Categoryid= "&
  eval (" CategoryID ")%> ' >
 </asp:HyperLink>
 -<%# eval (" Description ")% >
</li>

Notice the static url-productsforcategorydetails.aspx in the binding syntax? How categoryid-is concatenated directly with the results of eval ("CategoryID").

One advantage of using the hyperlink control is that you can programmatically access the ItemDataBound event handler of repeater if necessary. For example, you can display categories without associated product as text. Instead of link. Set the NavigateUrl property of the hyperlink of categories that have no associated product to an empty string so that category name appears as a text instead of link. For more information on formatting DataList and repeater content through ItemDataBound event handler, see the formatted DataList and repeater data. If you're following the tutorial, You can use both of these methods. When browsing this page, each category name is rendered as link, which links to the Productsforcategorydetails.aspx page and passes the value of CategoryID. See Figure 3.


Figure 3:category Names now links to productsforcategorydetails.aspx page

Step three: List the products under the selected category

After completing the Categorylistmaster.aspx page, we will now complete the "from" page, productsforcategorydetails.aspx. Open this page, drag a DataList control to come in, and set the ID to productsincategory. Then select Add a ObjectDataSource in the smart tag named Productsincategorydatasource. and Getproductsbycateg with PRODUCTSBLL class. Oryid (CategoryID) method to configure it. Select None in the Insert,update,delete tab.


Figure 4: Configuring the Getproductsbycategoryid (CategoryID) method using the Productsbll class ObjectDataSource

Because the Getproductsbycategoryid (CategoryID) method receives a parameter, the wizard prompts us to specify the source of the argument. Set parameter source to QueryString, Querystringfield for CategoryID.


Figure 5: Using the QueryString Field as the parameter Source

As you can see in the previous tutorial, when you complete the data source configuration, Visual Studio automatically creates a ItemTemplate that lists the name and value for each field. We only show name, Supplier and price. Set the DataList RepeatColumns property to 2. After completing these, your declaration should look similar to the following:

 <asp:datalist id= "productsincategory" runat= "Server" datakeyfield= "ProductID"
 repeatcolumns= "2" datasourceid= "Productsincategorydatasource" enableviewstate= "False" > <ItemTemplate>  
 

Now let's look at the effect and browse categorylistmater.aspx page. Then click link on the category listed. This will jump to the Productsforcategorydetails.aspx page, And pass the CategoryID through QueryString. Productsincategorydatasource ObjectDataSource returns the specified category's product and displays them in DataList , two per line. Figure 6 is a screenshot of the Click Beverages.


Figure 6: Two display beverages per line

Fourth Step: Display Category information in productsforcategorydetails.aspx

When the user clicks a category on the Categorylistmaster.aspx page, Jumps to the Productsforcategorydetails.aspx page and displays the product under the selected categry. However, in this page, there is no information on which category is selected. The user may want to point to beverages, But the result was condiments, and he couldn't figure out if he was wrong. To 剞 something bad behind this problem, we can display the selected category information at the top of the Productsforcategorydetails.aspx page ( Name and description). Add a FormView to the Productsforcategorydetails.aspx repeater. Then add a ObjectDataSource named Categorydatasource through the smart tag, It is configured using the Getcategorybycategoryid (CategoryID) method of the Categoriesbll class.


Figure 7: Configuring Categorydatasource

When the third step increases Productsincategorydatasource ObjectDataSource, the wizard prompts us for Getcategorybycategoryid (CategoryID) method to specify the input parameters. Here we use the same configuration as before, parameter source to Querystring,querystringfield set to CategoryID (see Figure 5).

When you complete the wizard, Visual Studio automatically creates itemtemplate,edititemtemplate and InsertItemTemplate for FormView. Because only a read-only interface is provided, We will EditItemTemplate and insertitemtemplate. Of course, you can also customize the ItemTemplate of FormView. Complete the above operation even your markup language should be similar to the following:

<asp:formview id= "FormView1" runat= "Server" datakeynames= "CategoryID" datasourceid= "Categorydatasource"
 Enableviewstate= "False" width= "100%" >
 <ItemTemplate>
  
 

Note: We also add a hyperlink to the FormView that will link the user back to the category page (categorylistmaster.aspx).


Figure 8:category Information displayed at the top of the page

Fifth step: If the selected category under No products will display a message

Regardless of the associated product,categorylistmaster.aspx page, all category are listed. If the user points to a category without product, because the data source is empty, The DataList in the Productsforcategorydetails.aspx page will not be displayed. In the previous tutorial we saw that the GridView provided a Emptydatatext attribute, Can be used to define a message when the data source has no records. Unfortunately, neither DataList nor Repeater has this attribute.

To prompt the user when category is not product We need to add a Label control to the page. Set its Text property to the information that you want to display when there is no matching product. We need to programmatically set its Visible property according to DataList. First add a Label control to the DataList. Set its ID to NOPR Oductsmessage,text is set to "There are no products for the selected category ...". Then we bind to productsincategory based on whether or not we have data DataList to set its Visible property. This step needs to be done after the data is bound to DataList. For Gridview,detailsview and FormView, we can create an event for the DataBound event Handler. Fires after the data is bound. However DataList and Repeater have no databound events.

In this example we can set the Visible property of the label in Page_Load event handling ... Because the data is bound to the DataList Load event before the page. However, this method does not work in general, because the data from ObjectDataSource is bound to DataList after the page cycle. If the data displayed is based on the value of another control, for example , as in the example of the master/detail table showing the master record using DropDownList, the data is not bound to the control until the page's life cycle is prerender.

A solution that works in all cases is to set visible to False in DataList ItemDataBound (or itemcreated) event handling. In this case, we know that there is at least one data item in the data source, Therefore, you can hide the Noproductsmessage Label. In addition to this event handler, we also need a DataList Databingd event handling, To initialize the label's Visible property to true. The Visible property of the label is initialized to True because the databinding time is fired after the ItemDataBound event. If there is data, it is set to false. See the following code:

protected void Productsincategory_databinding (object sender, EventArgs e)
{
 //show the Label
 Noproductsmessage.visible = true;
}
 
protected void Productsincategory_itemdatabound (object sender, DataListItemEventArgs e)
{
 //If We have a data it EM, hide the Label
 if (e.item.itemtype = = ListItemType.Item | |
 E.item.itemtype = = ListItemType.AlternatingItem)
 noproductsmessage.visible = false;
}

Category in the Northwind database are associated with one or more product. To test the functionality above, I manually modified the Northwind database to produce category (CATEGORYID=7) Product is associated with seafood category (CATEGORYID=8). You can select new query in Server Explorer and use the following statement:

UPDATE Products SET
 CategoryID = 8
WHERE CategoryID = 7

After updating the database, return to categorylistmaster.aspx page and point produce link. Since produce category has no products below, you will see "There are no product for the" Selected category ... "The hint, see Figure 9.


Figure 9: A prompt message appears when no product is selected under category

Summarize

Master/From records can be displayed on a page, can also be displayed separately on two pages. In this chapter we learned how to list category on the main page with repeater, listing the related product on the From page. Each item on the main page contains a link to the from page and passes the CategoryID value of the row.

In the "from" page through the Productsbll class of Getproductsbycategoryid (CategoryID) method returns the Product.categoryid parameter specified by the QueryString's CategoryID value. And we also use the category details in the "from" page with FormView, A message is displayed when the selected category does not have an associated product.

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.