Manipulating data in asp.net 2.0 29: Displaying Data by DataList and repeater-self-study process

Source: Internet
Author: User
Tags bind eval

Introduction

In the previous 28 tutorial examples, if we need to display multiple records for a data source, we use the GridView. A row of the GridView represents a record of the data source, and the column represents a field. Although the GridView is used to display data, paging, sorting, editing, removing is very convenient, but a little bloated. And the GridView structure is fixed-it contains a <tr> and <td> HTML <table> tags.

In order to have better customization when displaying multiple records, ASP.net 2.0 provides DataList and Repeater (also available in the ASP.net 1.x version). DataList and repeater use templates to display content, instead of using BoundFields, Checkboxfields, Buttonfields, and so on, as in the GridView. DataList Markup Language for HTML < Table>, but it allows each row to display more than one record. On the other hand, repeater does not generate extra markup languages, so if you want to control markup language generation precisely, it is the ideal choice.

In the following chapters, we'll begin by displaying the data using DataList and Repeater templates to learn their basic usage. We will learn how to control the format of these controls, how to change the layout of data in DataList, the most common master/detail scenarios, Ways to edit and delete data, and how to page pagination, and so on.

Step 1: Add DataList and Repeater Tutorials page

Before starting this tutorial, let's take the time to create some pages that will be used in this and later tutorials. First add a folder named Datalistrepeaterbasics, and then add the following page to make sure each page is selected Site.master as the motherboard page:

Default.aspx
Basics.aspx
Formatting.aspx
Repeatcolumnanddirection.aspx
Nestedcontrols.aspx

Figure 1: Creating the Datalistrepeaterbasics folder and adding pages

Open the Design view of the Default.aspx page, Drag the Sectionleveltutoriallisting.ascx user control in from the UserControls folder. The function provided by this user control is to list the tutorial chapters. We created it in the motherboard page and in the site navigation.

Figure 2: Adding Sectionleveltutoriallisting.ascx user controls to Default.aspx

Finally, add the addresses of these pages to the Web.sitemap entry. After paging and sorting <siteMapNode> adds the following tag.

<sitemapnode title= "displaying Data with the DataList and Repeater" description= "Samples of Reports ' use the Dat Alist and Repeater Controls "url=" ~/datalistrepeaterbasics/default.aspx "> <sitemapnode title=" Basic examples "D
 Escription= "examines the basics for displaying data using the DataList and Repeater." Url= "~/datalistrepeaterbasics/basics.aspx"/> <sitemapnode title= "Formatting description=" Learn How to format t
 He DataList and the Web controls within the DataList and Repeater ' s templates. Url= "~/datalistrepeaterbasics/formatting.aspx"/> <sitemapnode title= "Adjusting the DataList s Layout" Descripti
 On= "illustrates to alter the DataList's layout, showing multiple data source records per table row." Url= "~/datalistrepeaterbasics/repeatcolumnanddirection.aspx"/> <sitemapnode title= "Nesting a Repeater within a
 DataList "description=" Learn to nest a Repeater within the template of a DataList. Url= "~/datalIstrepeaterbasics/nestedcontrols.aspx "/> </siteMapNode>

 

Figure 3: Adding a new page to the Site map

Step Two: Display product information in DataList

Like FormView, DataList uses templates to display information, not BoundFields, Checkboxfields, and so on. Unlike FormView, DataList is used to display a set of records, Instead of a single one. Now let's start with the tutorials in this chapter. First look at how to bind product to DataList. Open the Basics.aspx page in the Datalistrepeaterbasics folder and drag a DataList from the Toolbox Come in. As shown in Figure 4, the designer is grayed out before you specify the template.

Figure 4: Dragging a DataList from the Toolbox into the designer

Open the smart tag for DataList, add a ObjectDataSource, and configure it using the GetProducts method of the Productsbll class. Because the DataList created in this tutorial is read-only, so in insert, UPDATE, and delete labels, select None in the Drop-down list.

Figure 5: Creating a new ObjectDataSource

Figure 6: Configuring the ObjectDataSource with the PRODUCTSBLL class

Figure 7: Using the GetProducts method to get all product information

After configuring ObjectDataSource in a smart tag and associating it with DataList, Visual Studio automatically creates a ItemTemplate for each field returned by the data source in DataList to display the name and value (see the code below). This default ItemTemplate looks the same as the template that is automatically generated when binding FormView.

<asp:datalist id= "DataList1" runat= "Server" datakeyfield= "ProductID" datasourceid= "ObjectDataSource1" Enableviewstate= "False" > <ItemTemplate> ProductID: <asp:label id= "ProductIdLabel" runat= "Server" text= ' & lt;%# Eval ("ProductID")%> '/><br/> ProductName: <asp:label id= "Productnamelabel" runat= "Server" Text = ' <%# Eval ("ProductName")%> '/><br/> SupplierID: <asp:label id= ' Supplieridlabel ' runat= ' server ' T
    Ext= ' <%# Eval ("SupplierID")%> '/><br/> CategoryID: <asp:label id= ' Categoryidlabel ' runat= ' server ' Text= ' <%# Eval ("CategoryID")%> '/><br/> quantityperunit: <asp:label id= ' Quantityperunitlabel ' runat= "Server" text= ' <%# Eval ("QuantityPerUnit")%> '/><br/> unitprice: <asp:label ID= ' UnitPriceLa Bel "runat=" Server text= ' <%# Eval ("UnitPrice")%> '/><br/> unitsinstock: <asp:label id= ' UnitsInSt Ocklabel "runat=" server "text= ' <%# Eval("UnitsInStock")%> '/><br/> unitsonorder: <asp:label id= ' Unitsonorderlabel ' runat= ' server ' Text= ' ;% # Eval ("UnitsOnOrder")%> '/><br/> reorderlevel: <asp:label id= ' Reorderlevellabel ' runat= ' server ' T Ext= ' <%# Eval ("ReorderLevel")%> '/><br/> discontinued: <asp:label id= ' Discontinuedlabel ' runat= '  Server "text= ' <%# Eval (" discontinued ")%> '/><br/> CategoryName: <asp:label id= ' Categorynamelabel ' runat= "Server" text= ' <%# Eval ("CategoryName")%> '/><br/> suppliername: <asp:label ID= ' SupplierNa Melabel "runat=" server "text= ' <%# Eval (" SupplierName ")%> '/><br/> <br/> </itemtemplate&gt
;
 </asp:DataList> <asp:objectdatasource id= "ObjectDataSource1" runat= "Server" oldvaluesparameterformatstring= "original_{0}" selectmethod= "GetProducts" typename= "ProductsBLL" > </asp:O Bjectdatasource>

Note: When you bind a data source to FormView through a smart tag, vistual Studio creates a ItemTemplate, a insertitemtemplate, and a edititemtemplate. However, for DataList, only one ItemTemplate will be created. This is because DataList, unlike FormView, has built-in editing and insertion capabilities. DataList not edit and delete related events, although to complete these functions, DataList is not as simple as FormView, we can still add a small amount of code to implement it. We'll talk about how to do the editing and deletion function in DataList in a future tutorial.

Let's take some time to improve the appearance of the template. We show only the name,supplier,category, quantity, and unit price of the product. And we use

<asp:datalist id= "DataList1" runat= "Server" datakeyfield= "ProductID" datasourceid= "ObjectDataSource1" Enableviewstate= "False" > <ItemTemplate>  

  Note: The above example uses a Label control with the text specified as the value of the data binding. Instead of using labels, we can just keep the data-bound code. In other words, we can use the <%# eval ("CategoryName")%> instead of <asp:label id= "Categorynamelabel" runat= "server" text= ' <%# 's eval ( "CategoryName")%> '/>

There are two benefits to using the label control, and the 1th in the next chapter is to provide a simple way to format the data. The 2nd is when you do not use Web controls, edit templates does not display the data-binding code that is declared. Through edit templates Interface makes it easy to manipulate static markup languages and Web controls, as long as all data bindings are implemented through the Edit DataBindings dialog box in the Web control's smart tag. Therefore, when using DataList, I recommend using a Label control so that you can pass the edit Templates can manipulate their content. We'll see that if you need to edit its contents when using repeater, you need to switch to the source view. When designing a repeater template, I usually don't use a Label control unless I need to format the appearance of the bound data.

Figure 8: Displaying product with DataList ItemTemplate

Step three: Improve the appearance of DataList

Like the GridView, DataList offers some properties related to style, such as font, ForeColor, BackColor, CssClass, ItemStyle, AlternatingItemStyle, SelectedItemStyle and so on. When using the GridView and DetailsView, we first created some skin files in DataWebControls theme, which predefined the cssclass of the two controls Properties and RowStyle, HeaderStyle and so on. We also take this approach when we use DataList.

As discussed in using the ObjectDataSource presentation data, a skin file defines the default display properties for a Web control. A theme is a collection of skin, CSS, image, and JavaScript files, It defines the appearance of a Web site. In the chapter using ObjectDataSource presentation data, we created a datawebcontrols Theme (App_Themes folder) that contains two skin files- Gridview.skin and Detailsview.skin. We are now going to add a third for DataList. Right-click the App_themes/datawebcontrols folder, select Add a New Item, select Skin File, Fill in the name with Datalist.skin.

Figure 9: Creating a skin file named Datalist.skin

Add the following markup language to the Datalist.skin.

<asp:datalist runat= "Server" cssclass= "Datawebcontrolstyle" >
 <alternatingitemstyle cssclass= " AlternatingRowStyle "/>
 <itemstyle cssclass=" RowStyle "/>  
 

The above is set DataList with the CSS file used by GridView and DetailsView. In Datawebcontrolstyle, AlternatingRowStyle, The CSS file used in RowStyle is defined in Styles.css.

After adding skin, the appearance of the DataList appears to change (you can choose to refresh the View menu to see the effect of the change). See figure 10,alternating The background color of product is pink.

Figure 10: Effect After adding a skin file

Fourth Step: Browse other Templates for DataList

DataList also supports 6 other types of template except ItemTemplate:

Headertemplate-used to render header row
Alternatingitemtemplate-used to render alternating items
Selecteditemtemplate-is used to render selected item; The index of selected item can be obtained by DataList SelectedIndex Property
Edititemtemplate-is used to render the edited item
Separatortemplate-used to separate individual item
FooterTemplate-Used to render footer row

When HeaderTemplate or FooterTemplate is specified, DataList adds a header or footer. Like the GridView, DataList Headers and footer are not bound to the data.

  Note: The header and footer do not support data-binding syntax, as we can see in the chapter on displaying statistics in the footer of the GridView, and data-bound information is available through the GridView RowDataBound event Handler to write. This technique can be used to technically bind data and or other information and to be displayed in footer. Similarly, it can be done in DataList and Repeater. The only difference is that the DataList and repeater The event handler (not RowDataBound) is created for ItemDataBound.

In our example, we display the title "Product Information" with

Figure 11: Adding the text as "Product information" HeaderTemplate

Similarly, adding the following code directly to the <asp:DataList> tag can also achieve the above purpose.

<HeaderTemplate>
  
 

To preserve some space between each of the listed product, we now add a separatortemplate .

<SeparatorTemplate>
 
 

Note: As with HeaderTemplate and Footertemplates, SeparatorTemplate is not bound to any data in the data source. Therefore, it is not possible to directly relate to the DataList bound data.

Now browsing the page in the browser should look similar to Figure 12. Note the line between the header and each product.

Figure 12:datalist now contains a line between the Header Row and each product

Fifth Step: Use Repeater

When browsing the example in Figure 12, you can look at the source file of the page. You will see the DataList contains <tr> and <td> html<table> this is actually the same as the GridView. We'll see in future tutorials, DataList allows more than one record to be displayed per line.

But what if you don't want to use html<table>? We'll use repeater. Repeater is also built on templates. It offers the following 5 kinds of template:

Headertemplate-the specified mark before the items
Itemtemplate-is used to render items
Alternatingitemtemplate-used to render alternating items
separatortemplate-the specified tag between the individual item
FooterTemplate-Add the specified tag after the items

In the ASP.net 1.x version. Repeater is typically used to display some data columns. In this case, HeaderTemplate and footertemplates contain a pair of <ul> tags, and ItemTemplate contains <li> and data binding syntax. This is also true for ASP.net 2.0, such as the example we see in the motherboard page and the site Navigation chapter:

In the Site.master master page, Repeater is used to display top-level site content (Basic Reporting, filtering Reports, customized formatting, and so on); Nested repeater are used to display the contents of a child area.
In the Sectionleveltutoriallisting.ascx user control, Repeater is used to display the contents of the child area of the current site zone.

  Note: ASP.net 2.0 can use BulletedList control. When using it, you do not need to specify any HTML related to the list. Instead, just specify the fields for each list item.

Repeater is an "almighty" control, and if you can't find a control that produces the markup language you need, you can use Repeater. Let's illustrate, Categoried is displayed on the DataList that displays the product information created in step two. We display each categorie as a column in a single html<table>. Drag a repeater from the toolbox. To the DataList that displays the product. Like DataList, the Repeater is grayed out before the templates are defined.

Figure 13: Adding a Repeater control

There is only one option in Repeater's smart tag: Select a data source. Create a ObjectDataSource, configure it with the GetCategories method of the Categoriesbll class.

Figure 14: Creating ObjectDataSource

Figure 15: Configuring ObjectDataSource with the Categoriesbll class

Figure 16: Using GetCategories method to get all categories information

Unlike DataList, Visual Studio does not automatically create ItemTemplate for repeater after binding to a data source. and repeater templates cannot be configured through the designer, only the page code can be written.

We use the following notation to display each category as a column in a single <table>:

<table>
 <tr>
  <td>category 1</td>
  <td>category 2</td>
  ...
  <td>category n</td>
 </tr>
</table>

Because the <td>category x</td> is part of the repetition, it is shown in the ItemTemplate of repeater. Mark before it <table><tr> will be placed in the HeaderTemplate, and the end tag </tr></table> will be placed in the FooterTemplate. The Source view button in the lower left corner of the designer enters the declaration code section of the ASP.net page, entering the following code:

<asp:repeater id= "Repeater1" runat= "Server" datasourceid= "ObjectDataSource2"
 enableviewstate= "False" >
 <HeaderTemplate>
  <table>
   <tr>
 </HeaderTemplate>
 < Itemtemplate>
    <td><%# Eval ("CategoryName")%></td>
 </ItemTemplate>
 <FooterTemplate>
   </tr>
  </table>
 </FooterTemplate>
</asp: Repeater>

Repeater contains exactly the tags specified in its template, and there is no spare part. Figure 17 shows how Repeater is viewed through the browser.

Figure 17: Listing each category in a single line of HTML <table> with a separate column

Step Sixth: Improve the appearance of repeater

Since repeater is an accurate representation of the tags specified in the templates, you should be able to imagine that it does not contain any style-related attributes. To change the appearance of the content produced by repeater, we need to manually add HTML or CSS to its templates.

In this case, we're going to do something like DataList alternating rows to change the background color of the category. We passed ItemTemplate and AlternatingItemTemplate To specify RowStyle CSS class for each Repeater item, AlternatingRowStyle CSS class for each alternating Repeater item, as in the following code:

<ItemTemplate>
 <td class= "RowStyle" ><%# Eval ("CategoryName")%></td>
</ itemtemplate>
<AlternatingItemTemplate>
 <td class= "AlternatingRowStyle" ><%# Eval (" CategoryName ")%></td>
</AlternatingItemTemplate>

We also add a header with the text "Product Categories". Since we don't know how many columns <table> will consist of, the simplest way to guarantee that the header can be generated across all columns is to use two <table The first <table> contains two rows of-header and one row containing the second <table>. Each category in the second <table> is a column.

<table>
 <tr>
  <th>product categories</th>
 </tr>
 <tr>
  <td>
   <table>
   <tr>
    <td>category 1</td>
    <td>category 2</td > ...
    <td>category n</td>
   </tr>
   </table>
  </td>
 </tr>
</table>

The following headertemplate and FooterTemplate produce the required tags:

<asp:repeater id= "Repeater1" runat= "Server" datasourceid= "ObjectDataSource2"
 enableviewstate= "False" >
 <HeaderTemplate>
  <table cellpadding= "0" cellspacing= "0" >
   <tr>
    <th class= " HeaderStyle ">product categories</th>
   </tr>
   <tr>
    <td>
     <table Cellpadding= "4" cellspacing= "0" >
      <tr>
 </HeaderTemplate>
 <ItemTemplate>
       <td class= "RowStyle" ><%# Eval ("CategoryName")%></td>
 </ItemTemplate>
 <AlternatingItemTemplate>
       <td class= "AlternatingRowStyle" >
        <%# Eval ("CategoryName")% ></td>
 </AlternatingItemTemplate>
 <FooterTemplate>
      </tr>
     </ table>
    </td>
   </tr>
  </table>
 </FooterTemplate>
</asp: Repeater>

In Figure 18 you can see the appearance of the repeater now.

Graph 18:category column background color alternating and Includes a Header Row

Summarize

Although it is easy to use the GridView to display, edit, delete, sort, and paging data, it is very bloated. To better control the appearance, we need to use DataList or repeater. These controls use templates to display records, not BoundFields .

DataList contains an HTML <table> By default, a row of the table displays a record of the data source, just like the GridView. We'll see in a later tutorial that DataList can be in a table The line represents more than one record. On the other hand, repeater strictly displays the tags specified in the templates. It does not add any additional information, so it is often used to display data in HTML elements other than <table>.

DataList and repeater provide greater flexibility in output, and they lack many built-in features compared to the GridView. In future tutorials we will see that there are some features that we can simply add. But remember, use DataList and repeater instead of the GridView, if you want to use these features, you have to implement them.

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.