Manipulate data in asp.net 2.0 30: Format DataList and Repeater data _ self-study Process

Source: Internet
Author: User
Tags bind

Introduction

In the previous tutorial we learned that DataList provides some style-style attributes. And we've also learned how to define Headstyle, ItemStyle, AlternatingItemStyle, The default CSS for attributes such as SelectedItemStyle. In addition to these four properties, DataList also provides other properties, such as font, ForeColor, BackColor, and borderwidth. And repeater does not provide any such attributes. If you need to use Reperter to achieve these effects, you need to write the markup language directly in the templates.

Typically, the format of what the data needs depends on the data itself. For example, we might use gray fonts to list the discontinued product or highlight when UnitsInStock equals 0. We've learned the GridView in the previous tutorial, DetailsView, and FormView both provide two distinct ways of formatting data.

DataBound event-Creates an appropriate event handler for the DataBound event, which is fired when data is bound to item (RowDataBound event for the GridView; for DataList and repeater. ItemDataBound event). In these events, the data just being bound can be formatted. See the chapter "Data-based custom formatting."

Templates Format Function-use Templatefields in DetailsView or GridView, or use template in FormView, we can asp.net class in Code-behind page In or BLL, or in any other Web program that can be invoked in the class library Riga format information. This formatting feature can receive arbitrary input parameters, but in template, for example, return HTML. The formatting feature was first used in the GridView control in the TemplateField chapter. Both of these methods can be used in both DataList and Repeater. In this chapter we'll take a step-by-step example of both of these controls.

Use ItemDataBound Event Handler

When data is bound to DataList, DataList DataBinding events are fired either by using a data source control or by using DataSource and DataBind () directly in your code. DataList creates a DataListItem object for each record of the data source, and then binds to the current record. In this process, DataList fires two events:

Itemcreated-is fired after creating the DataListItem
Itemdatabound-the current record is bound to DataListItem after it is fired

The following is a list of the approximate steps for the DataList data binding process

DataList's DataBinding event was triggered
DataList
Each record for the data source ...
For each record in the data source ...
Create a DataListItem object
Inspire ItemCreated Event
Bind Records to DataListItem
Inspire ItemDataBound Event
Add DataListItem to the Items collection

When data is bound to repeater, it is the same as the above. The only difference is that DataListItem changed to RepeaterItem.

  Note: Attentive readers may notice a slight difference between the sequence of steps DataList and repeater binding to data and the GridView. At the end of the data-binding process, the GridView fires the DataBound event. And neither DataList nor repeater the event.

As with the GridView, you can create an event handler for the ItemDataBound event to format the data. This event handler can handle data that has just been bound to DataListItem or RepeaterItem. To format as needed.

For DataList, you can format the item by using style-related attributes, such as font, ForeColor, BackColor, CssClass, and so on. And if you want to format the Web control in DataList, You need to program to get these controls and then control them. We've seen how to do it in the Custom formatting Based Upon Data. As with the Repeater control, the RepeaterItem class has no style-related properties, so You need to be programmed to implement it in ItemDataBound event handler.

Since the use of itemdatabound formatting techniques in DataList and repeater is inherently due, our example is mainly about DataList.

First step: Display product information in DataList

Before we learn to format, we first create a page that displays product information using DataList. In the previous chapter, we created a ItemTemplate display product name,category, supplier, The DataList of quantity and price. We'll do it again in this chapter. You can recreate the DataList and its ObjectDataSource, or copy the controls in the Basics.aspx in the previous chapter to the pages in this chapter ( formatting.aspx). When you have finished formatting.aspx, change the DataList ID from DataList1 to itemdataboundformattingexample. Below, Look at the DataList in the browser. As shown in Figure 1, the only format is the alternating background color of each product.

Figure 1: Listing product information in DataList

In this chapter, we will highlight the name and unit price of product that is less than $20.00 in yellow.

Step two: Programmatically determine the value of the data in ItemDataBound Event handler

Since only product with a price lower than $20.00 is formatted, we first have to judge the price of each product. When binding data to DataList, DataList creates a DataListItem instance for the record for each data source. and bind the data. When a record is bound to a DataListItem object, the ItemDataBound event is fired. We can create an event handler to determine the value of the current DataListItem, and then format the data based on that value.
Add the following code to create the ItemDataBound event for DataList

 protected void Itemdataboundformattingexample_itemdatabound (object sender,
 DataListItemEventArgs e) {if (E.item.itemtype = = ListItemType.Item | | E.item.itemtype = = ListItemType.AlternatingItem) {//programmatically reference the Productsrow instance//to T His datalistitem northwind.productsrow product = (Northwind.productsrow) ((System.Data.DataRowView) e.item.dataitem).
 Row; The UnitPrice is not NULL and less than $20.00 if (!product. Isunitpricenull () && product. UnitPrice <) {//Todo:highlight the product ' s name and Price}}} 
  

DataList's ItemDataBound event handler, conceptually and semantically, is the same as the RowDataBound event handler of the GridView (see Custom formatting based on data), There is a difference in grammar. When the ItemDataBound event fires, the DataListItem that just binds the data is passed to the associated event RowDataBound via E.item (E.row and handler in the GridView). DataList's ItemDataBound event handler affects every row, including header, footer, and separator. However, the product information is only bound to the data row. Therefore, before handling the ItemDataBound event , we first need to determine whether the data line is being processed. This can be done by checking the DataListItem itemtype property, which can have the following eight values:

AlternatingItem
EditItem
Footer
Header
Item
Pager
SelectedItem
Separator

Both item and AlternatingItem represent the DataList data item. Suppose we're dealing with item or AlternatingItem, We can get an instance of the Productsrow bound to the current DataListItem. The DataItem property of DataListItem contains a reference to the DataRowView object, which can be obtained by its row property.

Let's check the unit price attribute for the Productsrow instance. Because the UnitPrice field of the product table allows null values, we should first check that the value is empty before getting the UnitPrice property. If not, Let's check to see if it's below $20.00. If so, we'll do the formatting.

Step three: The Name and price highlighting for product

Once we find that product price is lower than $20.00, We're going to make its name and price appear highlighted. First, we'll program to get the label control that displays the name and price of product in ItemTemplate. Then we'll display the background color as yellow. This can be done directly by modifying the BackColor property of the label space (Labelid.backcolor = Color.yellow). Of course, the best way to do this is to have all the display-related behaviors done through CSS. In fact, we created the styles.css in the custom formatting chapter based on data- Affordablepriceemphasis has already provided this functionality.

Use the following code to set the CssClass property of the two label controls to Affordablepriceemphasis to complete the format:

Highlight the product name and unit price Labels
//-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 complete, browse the Formatting.aspx page in the browser. As shown in Figure 2, the name and prict of product with a price lower than $20.00 are highlighted.

Figure 2: Product with a lower price than $20.00 is highlighted

Note: Because DataList uses HTML <table>, the DataListItem instance has properties that can set the entire item style. For example, if we want to highlight all the item in yellow when Price is below $20.00, We can use E. Item.cssclass = "Affordablepriceemphasis" to replace the above code (see Figure 3).

The RepeaterItem, which makes up the repeater, does not provide such a property. Therefore, customizing the format in repeater needs to format the controls in the templates, as shown in Figure 2.

Figure 3:the Entire Product Item is highlighted to products Under $20.00

Using the formatting features of template

Using the TemplateField chapter in the GridView control, we learned how to use the GridView TemplateField formatting to format the GridView data. The format feature is a method that can be invoked from the template and returned to the HTML display. The formatting feature can be written in the Code-behind class of ASP.net page Or in the class file in the App_Code folder or in a separate class library project. If you want to use the same functionality in other ASP.net web programs or multiple asp.net pages, do not put it in the Code-behind class of ASP.net page.

To demonstrate this functionality, we will modify the product information. If product is deactivated, we add a "[discontinued]" text after product name. Similarly, if Price is lower than $20.00 We'll highlight it in yellow (as we did in the ItemDataBound event handler example). If price is equal to or higher than $20.00, we will not show actual prices, but display in text " Price Quote ". Figure 4 is a screenshot of the page that completes the above functionality.

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

First step: Create a formatting feature

In this example we need two formatting features, one of which is the "[discontinued]" after the deactivated product name, the second is highlighted for product with a price below $20.00, and the others show " Quote ". We will create these features in the Code-behind class of ASP.net page and name them displayproductnameanddiscontinuedstatus and Displayprice. Both methods need to return HTML and are marked as protected (or public) in order to be invoked in the ASP.net page's declaration syntax. The following are the code for the two methods:

 protected string Displayproductnameanddiscontinuedstatus (string productName, bool D
 iscontinued) {//return just the ProductName if discontinued be false if (!discontinued) return productName; else//Otherwise, return the ProductName appended and the text "[Discontinued]" return string.
Concat (ProductName, "[Discontinued]"); Protected string Displayprice (Northwind.productsrow product) {//If price are less than $20.00, return to the price, HIGHL ighted if (!product. Isunitpricenull () && product. UnitPrice <) 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&L
T;/span> "; }

Note that the Displayproductnameanddiscontinuedstatus method receives ProductName and discontinued values. And the Displayprice method receives Productsrow ( Rather than UnitPrice). If the formatting feature handles a measure that might contain null values for the database (such as UnitPrice, and ProductName and discontinued are not allowed), be particularly careful.

The value you enter may be a dbnull rather than the data type you expect, so the type of the input parameter must be object. And for example, check if the incoming value is database NULL. That is, if we want the Displayprice method to be a price parameter, We need the following code:

Protected string Displayprice (object UnitPrice)
{
 //If price are less than $20.00, return to the price, highlighted
   if (! Convert.isdbnull (UnitPrice) && ((decimal) UnitPrice <) 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 quo Te</span> ";
}

Note the type of the input parameter UnitPrice is object, and the conditional judgment statement is modified to determine if the UnitPrice is DBNull. Also, because UnitPrice is passed in as object, you must convert the type to decimal.

Step two: ItemTemplate call format method in DataList

After completing the above code, the rest of the work is to invoke these formatting features in the DataList ItemTemplate. We need to use the following code:

<%# MethodName (InputParameter1, InputParameter2, ...)%>

In the ItemTemplate of DataList, Productnamelabel label <%# Eval ("ProductName") by specifying the Text property%> The name of the product that is displayed. In order to add "[discontinued]" to the need, modify the code and use the Displayproductnameanddiscontinuedstatus method to specify the Text property. We need to use the eval ("ColumnName") syntax to pass the value of product name and discontinued. The value returned by Eval is type Object, and the Displayproductnameanddiscontinuedstatus argument is string and Boolean. Therefore, we need to convert the value returned by the Eval method to the desired parameter type, as follows :

 
 

As with the name of the product and the [discontinued] text, we set the Unitpricelabel label's property to the Displayprice return value to display the price. We take Productsrow as a parameter, Rather than UnitPrice:

<asp:label id= "Unitpricelabel" runat= "server" text=
 ' <%# displayprice ((northwind.productsrow)
   ( System.Data.DataRowView) Container.DataItem). Row)%> ' >
</asp:Label>

After completing the above code, look at the page in the browser. Your page should look similar to Figure 5.

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

Summarize

There are two ways to format DataList or repeater based on data. One is to create an event handler for ItemDataBound. ItemDataBound is fired when each record in the data source is bound to DataListItem or RepeaterItem. In ItemDataBound event handler, you can determine the current item's data and format it, For DataListItem, you can format the entire item.

The other is to complete the custom formatting by formatting the feature. The format feature is a method that can be invoked from the template and returned to the HTML display. Usually, Determines what HTML is returned by judging the value that is bound to the current item. These values, or objects bound to item, can be passed into the formatting function. 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.