Operating data in ASP.net 2.0 35: Using Repeater and DataList single page to achieve master/from report self-study process

Source: Internet
Author: User
Tags eval

Introduction

In the previous chapter we learned how to display master/detail information in two separate pages. In the main page we use repeater to display the category. Each category's name is a hyperlink that is linked to the from page. Displays the product under the selected category with a two-column DataList from the page. In this chapter we will still use a single page, display the category list on the left, and category's name is displayed with LinkButton. Click on one of the page postback, on the right side with two columns of DataList display related product. In addition to the name, the repeater on the left also displays the total number of product associated with the category. (See Figure 1)


Figure 1:category's Name and product totals appear on the left

First step: Display a repeater on the left side of the page

In this chapter we will display category on the left and the right table showing the product it is associated with. The content of a Web page can be positioned using standard HTML elements or CSS. So far we have used CSS to locate. In the master page and site Navigation Chapter, when we use absolute positioning to create a navigation, we specify a clear distance between the navigation list and the content. Of course, CSS can also be used to adjust the position of two elements.

Open the Categoriesandproducts.aspx page under the Datalistrepeaterfiltering folder and add a repeater and datalist.id to categories and categoryproducts, respectively. Then go to the source view and place them in the <div> element respectively. That is, add a closed </div> to the back of the repeater, and a start <div> before the DataList. Now your code should look similar to the following:

<div>
 <asp:repeater id= "Categories" runat= "Server" >
 </asp:Repeater>
</div>
<div>
 <asp:datalist id= "categoryproducts" runat= "Server" >
 </asp:DataList>
</div>

We need to use the Float property to put repeater on the left side of DataList, see the following code:

<div>
 Repeater
</div>
<div>
 DataList
</div>

Float:left the first <div> to the left of the second one. Width and padding-right Specify the distance between the first <div> width <div> content and the right border. For more information on floating elements, please refer to floatutorial. We create a new CSS class in Styles.css, called Floatleft (not set directly in the <p> style):

. Floatleft
{
 float:left;
 width:33%;
 padding-right:10px;
}

Then we use the <div class= "Floatleft" > Replace <div style= "Float:left" >.
When you have finished the above, switch to Design view. You should see that repeater is already on the left side of DataList (both controls are grayed out because no data source or template has been configured).


Figure 2: The page after the position is adjusted

Step Two: Get the total number of products associated with each category

Once you have finished styling, we are now binding category data to repeater. As shown in Figure 1, in addition to category name, we need to display the total number of product associated with it, in order to obtain this information we can:

Get this information in the Code-behind of ASP.net page. Based on the given CategoryID, we can get the associated product totals through the Getproductsbycategoryid (CategoryID) method of the Productsbll class. This method returns a Productsdatatable object whose Count property represents the information we need to know. We can create a ItemDataBound event handler for Repeater, call this method when each category is bound to repeater, and then output the total.

Update categoriesdatatable in the dataset to add a numberofproducts column. We can update the Categoriesdatatable getcategories () method to include this information or keep this method, and then create a new named Getcategoriesandnumberofproducts () method.

Let's take a look at both of these methods. The first one is easier to write because we don't need to update the DAL. But it needs to be more connected to the database. Invoking the Getproductsbycategoryid (CategoryID) method in ItemDataBound event handler adds a database connection (this occurs once per category binding). At this time there will be a n+1 request to the database (n is the total number of category shown in repeater). The second method of product total is returned from the GetCategories () () (or getcategoriesandnumberofproducts ()) method, so that only a single request to the database is possible.

Get total products in ItemDataBound Event handler

Get Total product totals in ItemDataBound event handler you do not need to modify the DAL. You only need to modify the Categoriesandproducts.aspx page directly. Add a new ObjectDataSource named Categoriesdatasource through the Repeater smart tag. Use the GetCategories () method of the CATEGORIESBLL class to configure it.


Figure 3: Configuring ObjectDataSource

Each of the category in the repeater is point-able, and categoryproducts DataList displays the associated product after the dot. We can set each category as hyperlink, link to this page (categoriesandproducts.aspx) and assign values to CategoryID through QueryString. The advantage of this approach is that specific category product can be indexed and bookmarked for search.

We can also set each category as LinkButton and we use this method in this chapter. LinkButton looks like a hyperlink, but clicks will produce a postback. The DataList ObjectDataSource is refreshed to display the selected category associated product. It is more reasonable to use hyperlink in this chapter. In other cases, however, it would be better to use LinkButton. Although this is the case, we also use LinkButton here. We'll see that using LinkButton will have some challenges that you won't be able to use hyperlink. So we can learn to learn it better for later use.

Note: It is best if you use Hyperlink or <a> instead of LinkButton to repeat the contents of this chapter.

The following markup languages are repeater and ObjectDataSource, noting that Repeater's template represents each item as LinkButton.

<asp:repeater id= "Categories" runat= "Server" datasourceid= "Categoriesdatasource" >
 
 

Note: The view state in this chapter repeater must be open (enableviewstate= "False" in Repeater's declarative syntax). in the third step we will create an event handler for the ItemCommand event, in which we will update the Seleceparameters collection of the DataList ObjectDataSource. If view state is disabled, the repeater ItemCommand will not be fired. For specific reasons and more information please refer to A stumper of an asp.net question and its solution.

LinkButton with ID viewcategory has not set the Text property yet. If we only need to display the category name, we can set it directly by binding syntax as follows:

<asp:linkbutton runat= "Server" id= "viewcategory"
 text= ' <%# Eval ("CategoryName")%> '/>

What we need to show here, however, is the total number of category's name and PROUDCT. See the following code:

 protected void Categories_itemdatabound (object sender, RepeaterItemEventArgs e) {//Make Su
  Re we ' re working with a data item ... if (E.item.itemtype = = ListItemType.Item | |
  E.item.itemtype = = ListItemType.AlternatingItem) {//Reference the Categoriesrow instance bound to this RepeaterItem Northwind.categoriesrow category = (Northwind.categoriesrow) ((System.Data.DataRowView) e.item.dataitem).
  Row; Determine how many products are in this category Northwindtableadapters.productstableadapter Productsapi = new Nor
  Thwindtableadapters.productstableadapter (); int productcount = Productsapi.getproductsbycategoryid (category. CategoryID).
  Count; Reference the Viewcategory LinkButton and set its Text property LinkButton viewcategory = (LinkButton) e.item.findcont
  Rol ("viewcategory"); Viewcategory.text = string. Format (' {0} ({1:n0}) ', category.
 CategoryName, ProductCount); } {          

We first want to make sure that we are dealing with the data item (itemtype or AlternatingItem) and then referencing the categoriesrow that is just bound to the current repeateritem. The Getcategoriesbyproductid (CategoryID) method is then invoked to get the number of record bars returned through the Count property. Finally, set the Text property of the Viewcategory LinkButton in ItemTemplate to "CategoryName (numberofproductsincategory)".

  Note: We can also write a formatting function in the code-behind of the ASP.net page, receive CategoryName and CategoryID values, and return the connection string for the total number of CategoryName and product. The result is then assigned directly to the LinkButton Text property without the need to handle the ItemDataBound event. More formatting functionality information references the use of TemplateField and formatting DataList and repeater data in the GridView control. After adding the event handler, look at the page in the browser. See Figure 4.


Figure 4: Show the total number of Name and products for each category

Update categoriesdatatable and Categoriestableadpter to include the total product totals for each category in addition to getting the total number of the product at each category bound to repeater We can also modify the categoriesdatatable and Categoriestableadapter in the DAL to include this information. We'll add a column to categoriesdatatable. Open app_code/dal/ Northwind.xsd, right-click DataTable, select Add/column. See Figure 5.


Figure 5: Adding a new column for Categoriesadatasource

This will add a column named Column1, and you can easily modify its name. Rename it to numberofproducts. Then we need to configure the properties of this column. Dot this column, To the Properties window. Change the datatype from System.String to System.Int32. Set the ReadOnly property to True. See Figure 6.


Figure 6: Setting the properties of the new column

Now the categoriesdatatable already contains the Numberofproducts column, but its value is not set. We can modify the GetCategories () method, Returns its information each time it gets category information. Here, because this is the only chapter that uses this data, let's create a new name for Getcategoriesandnumberofproducts (). Right-click Categoriestableadapter and select New query. The TableAdapter Query Configuration Wizard appears. Select SQL statement.


Figure 7: Selecting SQL Statement


Figure 8:sql Statement returns the number of rows

Next we need to write SQL statements. The following statement returns the total number of categoryid,categoryname,description and related product for each category:

Select CategoryID, CategoryName, Description,
  (select COUNT (*) from the products p WHERE P.categoryid = C.categoryid) 
   
    as numberofproducts from
Categories C
   


Figure 9: The SQL statement used

  Note the alias of the subquery that calculates the product total is numberofproducts. It is associated with the Categoriesdatatable numberofproducts column. The last step is to write the name of the method. Fill a The DataTable and return a DataTable are named Fillwithnumberofproducts and Getcategoriesandnumberofproducts.


Figure 10: Naming the new TableAdapter method

Now the DAL has been modified. Because all of our presentation layers, Bll,dal are called layers, so we need to add the corresponding Getcategoriesandnumberofproducts method in the Categoriesbll class.

[System.ComponentModel.DataObjectMethodAttribute
 (System.ComponentModel.DataObjectMethodType.Select, false)]
Public northwind.categoriesdatatable getcategoriesandnumberofproducts ()
{
 return Adapter.getcategoriesandnumberofproducts ();
}

After the Dal and BLL are complete, we will bind the data to categories Repeater. If you get the total number of products in the ItemDataBound Event handler In that section you have created a ObjectDataSource for repeater, deleted it, and then removed the DataSourceID attribute of the Repeater, as well as the ItemDataBound event. Repeater is now back to its initial state, Add a ObjectDataSource named Categoriesdatasource. Use the Getcategoriesandnumberofproducts () method of the CATEGORIESBLL class to configure it. See Figure 11.


Figure 11: Configuring ObjectDataSource

Then modify the ItemTemplate and use the data-binding syntax to bind the CategoryName and Numberofproducts fields to the LinkButton Text property. The complete markup language is as follows:

<asp:repeater id= "Categories" runat= "Server" datasourceid= "Categoriesdatasource" >
 
 

The page using this method looks the same as the previous one (see Figure 4).

Step three: Show selected category associated products

Now the portion of the category and product totals has been completed. Repeater displays each category as LinkButton, and when clicked produces postback, we need to display those associated product in Categoryproducts DataList.

One of the challenges we face now is how to display the product of a particular category in the DataList. In the master/from report chapter of the GridView and DetailView implementations we learned to create a girdview, and when one of its rows is selected, the The "from" information is displayed in the DetailsView on this page. ObjectDataSource of the GridView with Productsbll getproducts () Returns product information. and DetailsView's ObjectDataSource with Getproductsbyproductid (ProductID) Returns the selected product information. The ProductID parameter is provided by the SelectedValue property of the Girdview. Unfortunately, Repeater does not have a SelectedValue attribute.

  Note: This is one of the challenges of using LinkButton in repeater. If we use Hperlink, we can pass CategoryID through QueryString. Before we solve this problem, First bind the ObjectDataSource to DataList, and then specify ItemTemplate. Add a ObjectDataSource named Categoryproductsdatasource from the smart tag of the DataList and use the Getproductsbycategoryid of the Productsbll class ( Cateogryid) Configure it. Because this DataList only provides read-only functionality, select None in the Insert,update,delete tab.


Figure 12: Configuring ObjectDataSource

Because the Getproductsbycategoryid (CategoryID) method requires an input parameter, the wizard asks us to specify the parameter source. When we use the GridView or DataList to list categories, You can set the parameter source to Control,controlid as the ID of the data control. However, because Repeater does not have selectedvalue properties, it cannot be used as a parameter source. You can view the ControlID drop-down list, which contains only one control id- Categoryproducts (DataList).


Figure 13: Configuration Parameters

After you configure the data source, Visual Studio automatically generates ItemTemplate for DataList. Replaces the default ItemTemplate with the template that we used earlier. Set the DataList property of RepeatColumns to 2. After completing these, Your code should be similar to the following:

 <asp:datalist id= "categoryproducts" runat= "Server" datakeyfield= "ProductID" Datasourceid= "Categoryproductsdatasource" repeatcolumns= "2" enableviewstate= "False" > <ItemTemplate> < 
   h5><%# eval ("ProductName")%>       
 

So far Categoryproductsdatasource The ObjectDataSource CategoryID parameter has not been set. So there is no product displayed when browsing the page. We now need to set it to the CategoryID of the clicked Category in repeater. Here are two questions. , the first is how we can tell when Repeater's ItemTemplate is being ordered. Two is which is the point.

Like Button,imagebutton, LinkButton has a click event and a command event. The Click event is used only to indicate that LinkButton was clicked. Sometimes we need to send more information to the event handler. In this case, you need to use LinkButton CommandName and CommandArgument. When LinkButton is lit, the command event fires, and event handler accepts CommandName and CommandArgument values.

When a command event is fired in the template in the Repeater, the Rpeater ItemCommand event is fired. and will be clicked LinkButton (or button and ImageButton) CommandName and CommandArgument values. So, to judge category LinkButton when it was clicked, we need to:

Set the CommandName attribute of the ItemTemplate LinkButton in Rpeater (the "listproducts" I use). After the value is set, the command event is fired after the point is LinkButton.

Set the LinkButton CommandArgument property to the CategoryID of the current item.
Creates an event handler for the Repeater ItemCommand event. Inside it assigns the incoming CommandArgument value to the Categoryproductsdatasource The CategoryID parameter of the ObjectDataSource.

Below is a 1, 2 step mark. Notice how CategoryID is assigned to CommandArgument by binding syntax.

<ItemTemplate>
 <li>
  <asp:linkbutton commandname= "listproducts" runat= "Server"
   Commandargument= ' <%# Eval ("CategoryID")%> ' id= ' viewcategory ' text=
   ' <%# string. Format ("{0} ({1:n0})", _
    eval ("CategoryName"), eval ("Numberofproducts"))%> ' >
  </asp:linkbutton >
 </li>
</ItemTemplate>

Because any Button,linkbutton or ImageButton command event fires the ItemCommand event, creating the ItemCommand event at any time Handler first of all to carefully check the value of CommandName. And since we have only one LinkButton now, we may add a new button control to repeater, which fires the same itemcommand when clicked. Event handler. It is therefore best to ensure that CommandName is checked and then logically processed according to its value.

After ensuring that the value of the incoming commandname equals "Listproducts", event handler will Categoryproductsdatasource The ObjectDataSource CategoryID parameter is set to the incoming commandargument. SelectParameters changes to ObjectDataSource automatically cause DataList to be rebind to the data source. Displays the new selected category associated with the product.

protected void Categories_itemcommand (object source, RepeaterCommandEventArgs e)
{
 //If it ' s ' listproducts "Command that has been issued
 ... if (string. Compare (E.commandname, "listproducts", true) = = 0)
 {
  //Set The Categoryproductsdatasource ObjectDataSource ' s CategoryID parameter//to the CategoryID of the category this was
  just clicked (e.commandargument)
  ... Categoryproductsdatasource.selectparameters["CategoryID"]. DefaultValue =
   e.commandargument.tostring ();
 }
}

After this, this chapter is over! Now look at your page in the browser. Figure 14 is the first time you look at it. Because no category is selected, so no product is displayed. Click on a category, such as produce, The product associated with it is displayed in two columns. See Figure 15.


Figure 14: No product display when browsing the page for the first time


Figure 15: After clicking Produce Category, the related products are displayed on the right .

Summarize

We learned in this chapter and in the previous chapter that the master/from table can be displayed separately on two pages or together on a page. If it appears on a page, we need to consider how to control their appearance. master/DetailView implementations using the GridView and the From the report chapter we will display the record on top of the master record, and in this chapter we use CSS to display the master record on the left side of the record. We also explored how to get the number of product associated with each category, and the LinkButton in the Click Repeater ( or Buttonimagebutton), the server-side processing logic.

To this end, use DataList and repeater to show that the master/from table is complete. We'll show you how to add edit and delete functionality to the DataList.

I wish you a happy programming!

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.