ASP. NET 2.0 data tutorial thirty formatting datalist and repeater data

Source: Internet
Author: User
Introduction

In the previous tutorial, we learned that datalist provides some style attributes. we also learned how to define default CSS for attributes such as headstyle, itemstyle, alternatingitemstyle, and selecteditemstyle. in addition to these four attributes, datalist also provides other attributes, such as font, forecolor, backcolor, and borderwidth. the repeater does not provide any such attribute. if you need to use reperter to achieve these effects, you need
Directly write the markup language in templates.

Generally, the data format depends on the data itself. for example, we may use a gray font to list products that are not used, or highlight them when unitsinstock is equal to 0. in the previous tutorial, we have learned two completely different ways to format data: gridview, detailsview, and formview.

    • Databound event-create an appropriate event handler for the databound event, which is triggered when data is bound to the item (rowdatabound event for the gridview; itemdatabound event for datalist and repeater ). in these events, the bound data can be formatted. see data-based custom formatting.
    • Formatting of templates-use templatefields in detailsview or gridview, or use template in formview. NET page code-behind class or Bll, or any other WebProgramAdd the formatting information to the class library that can be called. this Formatting Function can receive arbitrary input parameters, but in the template, for example, HTML is returned. the formatting function was first mentioned in the chapter templatefield used in the gridview control.

Both methods can be used in datalist and repeater. In this chapter, we will use these two methods step by step for examples in these two controls.

Use itemdatabound event handler

When data is bound to datalistCodeUsing datasource and databind () in datalist, The databinding event of datalist will be fired. datalist creates a datalistitem object for each record of the data source and binds it to the current record. in this process, datalist triggers two events:

    • Itemcreated-triggered after datalistitem is created
    • Itemdatabound-triggered when the current record is bound to datalistitem

The following lists the general steps of the datalist data binding process.

    1. The databinding event of datalist is triggered.
    2. Datalist
      Each record of the data source...
      For each record in the data source...
      1. Create a datalistitem object
      2. Trigger itemcreated event
      3. Bind record to datalistitem
      4. Trigger itemdatabound event
      5. Add datalistitem to items collection

When data is bound to a repeater, the only difference is that datalistitem is changed to repeateritem.

Note: careful readers may notice that the order of the steps when datalist and repeater are bound to data is slightly different from that of gridview. later in the data binding process, the gridview will trigger the databound event, and neither datalist nor repeater has this event.

Like the gridview, you can create an event handler for the itemdatabound event to format the data. This event handler can process the data just bound to datalistitem or repeateritem and format it as needed.

For datalist, you can use style-related attributes such as font, forecolor, backcolor, and cssclass to format items. if you want to format the Web controls in the template in datalist, You Need To program these controls and then control them. we have seen how to do this in the M formatting based upon data chapter. like the Repeater control, the repeateritem class does not have style-related attributes. Therefore, you need to program it in itemdatabound event handler.

Since the itemdatabound formatting technology is used in datalist and repeater, the following example mainly describes datalist.

Step 1: display product information in datalist

Before we worry about the formatting, let's first create a page that uses a datalist to display product information. in the previous tutorial we created a datalist whose itemtemplate displayed each product's name, category, supplier, quantity per unit, and price. let's repeat this functionality here in this tutorial. to accomplish this, you can either recreate the datalist and its objectdatasource from scratch, or you can copy over those controls from the page created in the previous tutorial (basics. aspx) and paste them into the page for this tutorial (formatting. aspx ).

Before learning formatting, we first create a page that uses datalist to display product information. in the previous chapter, we created an itemtemplate to display the datalist of product name, category, supplier, quantity, and price. we will repeat it once in this chapter. you can recreate datalist and its objectdatasource, or directly add the basics in the previous chapter. the control in aspx is copied to the page (formatting. in aspx.

After formatting. aspx is completed, change the datalist ID from datalist1 to itemdataboundformattingexample.
Next, let's look at datalist.1 in the browser. The only format is the alternate background color of each product.

Figure 1: Listing product information in datalist

In this chapter, we will highlight the names and unit prices of products with prices less than $20.00 in yellow.

Step 2: Program and judge the data value in itemdatabound event handler

Because only products with prices lower than $20.00 will be formatted, we must first determine the price of each product. when binding data to datalist, datalist creates a datalistitem instance for each data source record and binds the data. when the record is bound to the datalistitem object, the itemdatabound event is triggered. we can create an event handler for this event to judge the value of the current datalistitem, and then format the data based on this value.

Create an itemdatabound event for the datalist and add the following code:
Add the following code to create an itemdatabound event for datalist:

C #
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
Protected void itemdataboundformattingexample_itemdatabound (Object sender, datalistitemeventargs e) {If (E. item. itemtype = listitemtype. item | E. item. itemtype = listitemtype. alternatingitem) {// programmatically reference the productsrow instance bound to this datalistitem northwind. productsrow Product = (northwind. productsrow) (system. data. datarowview) E. item. dataitem ). row; // see if the unitp Rice is not null and less than $20.00 if (! Product. isunitpricenull () & product. unitprice <20) {// todo: highlight the product's name and price }}}

In terms of concept and semantics, itemdatabound event handler of datalist is similar to rowdatabound event handler of gridview (see custom data-based formatting). There is a difference in syntax. when the itemdatabound event is triggered, the datalistitem that is just bound to the data passes through E. item (E. row and rowdatabound) to the relevant event handler. the itemdatabound event handler of datalist affects each row, including Header, footer, and separator. however, the product information is only bound to the data row. therefore, before processing the itemdatabound event, we must first determine whether the processing is a data row. this can be done by checking the itemtype attribute of datalistitem. It can have the following eight values:

    • Alternatingitem
    • Edititem
    • Footer
    • Header
    • Item
    • Pager
    • Selecteditem
    • Separator

Item and alternatingitem both represent the data item of datalist. assume that we are processing item or alternatingitem, we can obtain the productsrow instance bound to the current datalistitem. the dataitem attribute of datalistitem contains the reference of the datarowview object. You can obtain the productsrow object through its row attribute.

Next we will check the unit price attribute of the productsrow instance. because the unitprice field of the product table allows null values, we should first use the isunitpricenull () method to check whether the value is null before getting the unitprice attribute. if not, check whether it is lower than $20. 00. if yes, we will format it.

Step 3: highlight the product name and price

Once we find that the price of a product is lower than $20.00, we will highlight its name and price. first, we need to program the label control that shows the product name and price in itemtemplate. then, the background color is yellow. you can directly modify the backcolor attribute (labelid. backcolor = background-affordablepriceemphasis already provides this function.

Use the following code to set the cssclass attribute of the two label controls to affordablepriceemphasis for formatting:

C #
1 2 3 4 5 6 7 8 9 10 11
// Highlight the product name and unit price labels // first, get a reference to the two label Web controls label productnamelabel = (Label) E. item. findcontrol ("productnamelabel"); label unitpricelabel = (Label) E. item. findcontrol ("unitpricelabel"); // next, set their cssclass properties if (productnamelabel! = NULL) productnamelabel. cssclass = "affordablepriceemphasis"; if (unitpricelabel! = NULL) unitpricelabel. cssclass = "affordablepriceemphasis ";

After the itemdatabound event is completed, browse the formatting. ASPX page in the browser, as shown in. 2. The name and prict of the product whose price is lower than $20.00 are highlighted.

Figure 2: products with prices lower than $20.00 are highlighted

Note: Because datalist uses HTML <Table>, datalistitem instances can set attributes of the entire item style. for example, if we want to highlight all items in yellow when the price is lower than $20.00, we can use E. item. cssclass = "affordablepriceemphasis" to replace the above Code (see figure 3 ).

The repeateritem that makes up the repeater does not provide such attributes. Therefore, the custom format in the repeater needs to set the control format in the templates, as shown in figure 2.

Figure 3: The entire product item is highlighted for products under $20.00

Use the template Formatting Function

In the use of templatefield in the gridview control, we learned how to use the Formatting Function of the gridview templatefield to format the data of the gridview. the formatting function is a method that can call from the template and return HTML display. the formatting function can be written in ASP.. NET page code-behind class or the class file in the app_code folder or in a separate class library project. if you want.. NET web program or multiple ASP. NET page uses the same function, so do not put it in ASP. NET page code-behind class.

To demonstrate this function, we will modify the product information. if the product is disabled, we add a text of "[Discontinued]" after the product name. similarly, if the price is lower than $20.00, it will be highlighted in yellow (as we did in the itemdatabound event handler example ). if the price is equal to or higher than $20.00, the actual price will not be displayed, but "Please call for a price quote" will be displayed in text ". figure 4 shows the page for completing the preceding functions.

Figure 4: replace the prices of more expensive products with the text "Please call for a price quote.

Step 1: Create a Formatting Function

In this example, we need two formatting functions. One is to add "[Discontinued]" after the disabled product name, and the other is to highlight the product with a price lower than $20.00, for others, "Please call for a price quote" is displayed ". in ASP. create these functions in the code-behind class of net page and name them displayproductnameanddiscontinuedstatus and displayprice. both methods need to return HTML, and in order. all calls in the Declaration Syntax of net page must be marked as protected (or public ). the code for these two methods is as follows:

C #
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19 20
Protected string displayproductnameanddiscontinuedstatus (string productname, bool discontinued) {// return just the productname if discontinued is false if (! Discontinued) return productname; else // otherwise, return the productname appended with the text "[Discontinued]" Return string. concat (productname, "[Discontinued]");} protected string displayprice (northwind. productsrow product) {// if price is less than $20.00, return the price, highlighted if (! Product. isunitpricenull () & product. unitprice <20) return string. concat ("<SPAN class = \" affordablepriceemphasis \ ">", product. unitprice. tostring ("C"), "</span>"); else // otherwise return the text, "Please call for a price quote" return "<span> Please call for a price quote </span> ";}

Note that the displayproductnameanddiscontinuedstatus method receives the values of productname and discontinued. the displayprice method receives productsrow instead of unitprice ). if the Formatting Function may contain values with null values (such as unitprice, which cannot be null for both productname and discontinued), take special care.

The input value may be dbnull rather than the expected data type. Therefore, the type of the input parameter must be object. for example, check whether the passed value is database null. that is to say, if we want the displayprice method to take the price as the parameter, we need the following code:

C #
1 2 3 4 5 6 7 8 9 10
Protected string displayprice (Object unitprice) {// if price is less than $20.00, return the price, highlighted if (! Convert. isdbnull (unitprice) & (decimal) unitprice) <20) return string. concat ("<SPAN class = \" affordablepriceemphasis \ ">", (decimal) unitprice ). tostring ("C"), "</span>"); else // otherwise return the text, "Please call for a price quote" return "<span> Please call for a price quote </span> ";}

Note that the type of the input unitprice parameter is object, and the condition judgment statement is modified to judge whether unitprice is dbnull. Moreover, since unitprice is passed in as an object, the type must be converted to decimal.

Step 2: Call the formatting method in the itemtemplate of datalist

After the above Code is completed, the rest of the work is to call these formatting functions in the itemtemplate of datalist. We need to use the following code:

ASP. NET
1
<% # Methodname (inputparameter1, inputparameter2,...) %>

In itemtemplate of datalist, productnamelabel label specifies the name of the product whose text attribute is <% # eval ("productname") %>. to add "[Discontinued]" as needed, modify the code and use the displayproductnameanddiscontinuedstatus method to specify the text attribute. we need to use the eval ("columnname") syntax to pass the product name and discontinued values. the value returned by Eval is of the object type, while the parameters of displayproductnameanddiscontinuedstatus are string and Boolean. therefore, we need to convert the value returned by the eval Method to the required parameter type. The Code is as follows:

ASP. NET
1 2 3 4 5
<H4> <asp: Label id = "productnamelabel" runat = "server" text = '<% # displayproductnameanddiscontinuedstatus (string) eval ("productname"), (bool) eval ("discontinued") %> '> </ASP: Label> </H4>

Like displaying the product name and the "[Discontinued]" text, we set the unitpricelabel label attribute to the returned value of displayprice to display the price. We use productsrow as the parameter instead of unitprice:

ASP. NET
1 2 3
<Asp: Label id = "unitpricelabel" runat = "server" text = '<% # displayprice (northwind. productsrow) (system. data. datarowview) container. dataitem ). row) %> '> </ASP: Label>

After the above Code is completed, check the page in the browser. Your page should look similar to figure 5.

Figure 5: Replace the prices of more expensive products with the text "Please call for a price quote"

Summary

There are two methods to format datalist or repeater based on data. one is to create event handler for itemdatabound. itemdatabound is triggered when each record of the data source is bound to datalistitem or repeateritem. in itemdatabound event handler, you can determine the data of the current item and format it. For datalistitem, You Can format the entire item.

The other is to use the Formatting Function to complete custom formatting. the formatting function is a method that can call from the template and return HTML display. generally, the returned HTML is determined by determining the value bound to the current item. these values or objects bound to items can be passed to the Formatting Function.

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.