You need to use a unique data-bound control. Fritz Onion
Code Location: Extremeaspnet2008_03.exe (192 KB)
Browse the Code Online
Folder ListView Basics
ListView and CSS
Page out
Sorting, editing, inserting, and deleting
Group
Start running the ListView
With Visual Studio®20,081 the new data-bound control-listview is introduced with the published ASP. NET 3.5.
I know what you're thinking: Why is there still a data-bound control in ASP. When displaying data collection, we already have more than 10 controls to choose from, including a DataGrid that is no longer in use, a new and improved GridView, a reliable and simple Repeater, a unique and flexible DataList, a convenient FormView And a slightly redundant peer DetailsView.
Of course. Another dimension list controls BulletedList, ListBox, DropDownList, RadioButtonList, and CheckBoxList. In theory, the ListView can replace all other data-bound controls in ASP. There is no doubt about this point. You can use the ListView control to replace each of the other controls in the list above.
The ListView also makes it easier to work with data binding tasks than the first few controls, including CSS styling, flexible paging, and good sorting, inserting, deleting, and updating features. We let you introduce the typical usage patterns of the ListView, and then explain the functionality of the control, demonstrating its flexibility and powerful capabilities. At the end of this column, you will have enough information to determine how many data-bound controls should be retained in your ASP.
The ListView base ListView is a template-driven control, which means that it does not render whatever data by default-you must specify the HTML you want it to render in the form of a template. Like most template controls, ItemTemplate will be the focus of your work. You need to put the HTML content of each row in the bound dataset in ItemTemplate.
The new feature in the ListView, and also its real difference from other controls, is the introduction of LayoutTemplate. In LayoutTemplate, you can define the top-level HTML you want to output as the content that the control renders. For example, suppose you want the ListView to be rendered as a table. It is possible to include top <table> and <thead> elements in LayoutTemplate, leaving the presentation of rows and cells to ItemTemplate. As you can see in Figure 1 (In this demo sample, the bound data source will display a simple table that includes the movie title and the release date). Figure 2 shows the browser rendering.
Figure 1 Using layouttemplate and ItemTemplate copy code
Datasourceid= "_moviesdatasource" >
<LayoutTemplate>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>release date</th>
</tr>
</thead>
<tbody>
<asp:placeholder runat= "Server" id= "Itemplaceholder"/>
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval ("movie_id")%></td>
<td><%# Eval ("title")%></td>
<td><%# Eval ("Release_date", "{0:d}")%></td>
</tr>
</ItemTemplate>
</asp:ListView>
Figure 2
list that appears in the table(Click the image for a larger view) The association between LayoutTemplate and ItemTemplate is completed by a single server-side control with the ID set to Itemplaceholder in LayoutTemplate. (You can use the Itemplaceholderid property of the ListView to change the default value of the ID string.) In the first demo sample, I put an instance of the PlaceHolder control in the template. That's where I want to inject ItemTemplate content. Note: Although child controls must be supported, there is no limit to what type of control must be used as a placeholder--id is important. For example, I was able to write layouttemplate using the server-side table row instead of the PlaceHolder control. Achieve the same effect: copy code
<LayoutTemplate>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>release date</th>
</tr>
</thead>
<tbody>
<TR runat= "Server" id= "Itemplaceholder"/>
</tbody>
</table>
</LayoutTemplate>
usually. For the following two reasons. I prefer to use a generic PlaceHolder control.
The first reason is that the names match very well. And. The control does not render its own HTML, but instead replaces it with ItemTemplate content, so it is more logical to assume that the control has no other purpose than preserving its position in the hierarchy. Of course, the reason that the ListView is so flexible is that you have complete control over the contents of the LayoutTemplate. You are not only able to use the table-you can place HTML whatever you wish to render in LayoutTemplate, but only when you inject the Itemplaceholder control location ItemTemplate the content is valid.
The following is a sample of the ListView that is bound to the same movie data source, but this time it is not a table, and the movie with the title and release date is displayed in the bulleted list (the result list is shown in Figure 3 ): The same list as the 3 . copy code in different formats (click the image for a larger view)
<asp:listview runat= "Server"
Datasourceid= "_moviesdatasource" >
<LayoutTemplate>
<ul>
Id= "Itemplaceholder"/>
</ul>
</LayoutTemplate>
<ItemTemplate>
<%# Eval ("Release_date", "{0:d}")%> </li>
</ItemTemplate>
</asp:ListView>
The ListView and cssasp.net developers have long been constrained by individual controls when creating CSS-driven Web sites. Many default controls render inline styles. Or it is difficult to associate a CSS class with its HTML output part.
In fact, Microsoft published a toolkit called "CSS Control adapters" in April 2006, which provides an optional rendering mechanism for several fully CSS-driven controls, including the GridView, to help correct the problem (for specific information, see the October 2006 Very ASP. "Column msdn.microsoft.com/msdnmag/issues/06/10/extremeaspnet).
These alternate rendering mechanisms have never been incorporated into the full version, so they need to be installed separately and without designer support. The ListView makes it easier to make use of CSS in your Web site by giving you complete control over when and where to apply style sheets.
A common scenario is for developers to manually pre-design a specific page. Usually includes HTML and CSS. It is always very difficult to ensure that the specific design of the data table with the traditional GridView is correct, since the GridView class only provides a limited set of hooks for altering the HTML results.
I've seen many experiments and mistakes that developers have experienced. Apply style attributes to the grid, view the source of the page to understand exactly where the style is placed, and repeat the experiment until the grid can be rendered as required. Use the ListView. You don't have to do this work anymore, because you can now control the layout and content.
For example, if the table provided to you needs to be displayed in the way shown in Figure 4 and uses a design consisting of. htm and. css files, as seen in Figure 5 . Figure 5 HTML and CSS for the Table
HTML Copy Code
<div class= "Prettygrid" >
<table cellpadding= "0" cellspacing= "0" summary= "" >
<thead>
<tr>
<th scope= "col" ><a href= "http://." >ID</a></th>
<th scope= "col" ><a href= "http://." >Title</a></th>
<th scope= "col" ><a href= "http://." >release date</a></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>where the Wild things are</td>
<td>12/15/2008</td>
</tr>
<!--...-->
</tbody>
</table>
<div class= "Pagination" >
<span>1</span>
<a href= "http://." >2</a>
<a href= "http://." >3</a>
</div>
</div>
CSSCopy Code
. Prettygrid
{
width:100%;
}
. Prettygrid Div. Pagination,
. Prettygrid Div. Pagination A,
. Prettygrid Div. Pagination span
{
Color: #00FFFF;
Background: #284775;
Font-weight:normal;
padding:2px;
}
. Prettygrid table
{
Border:solid 1px #CCCCCC;
width:100%;
}
/*...*/
Figure 4
Table Target Design(Click the image for a larger view) you can select the appropriate part from the HTML. and put it in the appropriate template, to create a high-speed ListView can accurately according to the requirements of the HTML/CSS combination, such as
Figure 6What you see. Finally the result will be exactly the same as when you use CSS to set HTML styles entirely.
Just updating the HTML or the corresponding CSS will make it very easy to change the design. Figure 6 ListView to Construct the Table copy code
<asp:listview id= "_moviesgrid" runat= "Server" datakeynames= "movie_id"
Datasourceid= "_moviesdatasource" >
<LayoutTemplate>
<div class= "Prettygrid" >
<table cellpadding= "0" cellspacing= "0" summary= "" >
<thead>
<tr>
<th scope= "col" ><a href= "http://." >id</a ></th>
<th scope= "col" ><a href= "http://." >Title</a></th>
<th scope= "col" ><a href= "http://." >release date</a></th>
</tr>
</thead>
<tbody>
<asp:placeholder id= "Itemplaceholder" runat= "Server"/>
</tbody>
</table>
<div class= "Pagination" >
<span>1</span>
<a href= "http://." >2</a>
<a href= "http://." >3</a>
</div>
</div>
</LayoutTemplate>
<AlternatingItemTemplate>
<tr class= "Alternate" >
<td><asp:label id= "Movie_idlabel" runat= "Server"
Text= ' <%# Eval ("movie_id")%> '/></td>
<td><asp:label id= "Titlelabel" runat= "Server"
Text= ' <%# Eval ("title")%> '/></td>
<td><asp:label id= "Release_datelabel" runat= "Server"
Text= ' <%# Eval ("Release_date", "{0:d}")%> '/> </td>
</tr>
</AlternatingItemTemplate>
<ItemTemplate>
<tr>
<td><asp:label id= "Movie_idlabel" runat= "Server"
Text= ' <%# Eval ("movie_id")%> '/></td>
<td><asp:label id= "Titlelabel" runat= "Server"
Text= ' <%# Eval ("title")%> '/></td>
<td><asp:label id= "Release_datelabel" runat= "Server"
Text= ' <%# Eval ("Release_date", "{0:d}")%> '/> </td>
</tr>
</ItemTemplate>
</asp:ListView>
Pagination and sorting are included in the original HTML design introduced at the beginning of the previous section, so the task of fully implementing the grid according to the specification has not been completed.
Let's split the page first and then sort it again. Pagination in the ListView control is implemented by introducing a new control DataPager. By isolating paging in a separate control, DataPager separates the paging UI from the page that the ListView uses to render the data. This means that you can place the paging UI anywhere on the page and be able to create as many DataPager controls as you wish.
Pagination control a common application is to provide a paging interface at the top and bottom of the data grid so that users can navigate to the next page without scrolling the grid--datapager can do this very easily. Let's first implement paging in the ListView Demo sample in the previous section. The easiest way to create the DataPager control associated with a ListView is to actually embed the DataPager control in the LayoutTemplate of the ListView: Copy Code
<asp:listview id= "_moviesgrid"
Datasourceid= "_moviesdatasource" >
<LayoutTemplate>
<!--...-->
<div class= "Pagination" >
<asp:datapager id= "_moviesgriddatapager" runat= "Server" >
<Fields>
<asp:numericpagerfield/>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
By embedding the DataPager in the layouttemplate of the ListView. They create inner connections.
Another way is to place DataPager in a different location on the page and associate it with the ListView by setting its pagedcontrolid to the ID of the associated ListView. In such a special case. Numericpagerfield exactly what I wanted-a series of numbers displayed as hyperlinks to navigate to the page. DataPager supports three types of fields:
- Numericpagerfield Display 1 2 3 ... Paging interface.
- Nextpreviouspagerfield displays "Next" (next), "Previous" (previous), "First" (Page one) and "last" (final) button to and fro between rows.
- Templatepagerfield lets you use the PagerTemplate definition to precisely design and implement the functionality of the paging interface.
Under normal circumstances. The DataPager control is used to provide paging support for any control that implements the IPageableItemContainer interface (currently the ListView is the only control that implements the interface). For example, see the following: Copy code
public interface IPageableItemContainer
{
Event eventhandler<pageeventargs> Totalrowcountavailable;
BOOL DataBind);
int maximumrows {get;}
int startRowIndex {get;}
}
Figure 7 shows the relationship between the ListView, DataPager, and the associated DataSource control. Instead of interacting directly with the DataSource used to populate the ListView, DataPager queries the required data through the interface.
Figure 7 The relationship between the ListView, DataPager, and DataSource (click the image for a larger view) is the ListView query DataSource to see if it supports paging when you are ready to page out. Assume support. Whether it can return the total number of rows. Suppose you can return the total number of rows. The ListView retrieves the total number of rows in the data source and then raises the Totalrowcountavailable event, which is implemented as part of its IPageableItemContainer interface. Whatever associated DataPager control will subscribe to the event. and use the total number of rows to initialize the fields required to display the paging interface.
DataPager will then call the ListView's Setpageproperties method to set the initial row index and the maximum number of rows to return.
When the ListView retrieves data from the associated data source, it simply requests a subset of the rows based on the value set by DataPager. Whenever DataPager changes its current page index (usually because of user interaction), it will call the ListView setpageproperties again to reflect the current subset of rows that need to be retrieved. The ability to change the number of record bars displayed on a page by setting the PageSize property of the DataPager control affects the maximum number of rows set in the associated ListView information.
DataPager also supports the Querystringfield property. This property can radically change the way DataPager works. By setting the Querystringfield property to some string (such as Pagenum). Indicates that you requested DataPager to send an HTTP GET request in response to a user clicking on a page number. The requested page number is sent through the query string parameters of the string you specify, rather than through the traditional POST postback mode.
Another advantage of this change is that it allows the client to create bookmarks to a specific page in a data-bound ListView control, because the page number can be seen in the URL. Please note that. Assume that you switch to such a Get communication mode. The POST postback hook mechanism used by the ASP. NET AJAX UpdatePanel control cannot intercept paging requests. and turns it into an asynchronous postback: copy code
<asp:datapager id= "_moviesgriddatapager" runat= "Server"
querystringfield= "Pagenum" >
<Fields>
<asp:numericpagerfield/>
</Fields>
</asp:DataPager>
Note: Because DataPager relies entirely on the ListView to run the actual data paging, and the ListView relies on the DataSource control, there is the same paging limit for other data-bound controls. For example, for SqlDataSource controls. This means that the entire result set needs to be loaded into memory to run paging, only when it is set to DataSet mode. Of course, you can define your own pagination using your own DataSource control or using the ObjectDataSource control.
Sorting, editing, inserting, and deleting assume that the ListView does not have a support for sorting and complete creation, read, update, and delete (CRUD) operations, then it is incomplete. It implements each command in a manner similar to the way the FormView control implements the command. Since the ListView is completely driven by the template. So for its template, set the CommandName property to one of the following seven specific command strings. Can be identified: Cancel (cancel), delete (delete), select (selection), edit (edit), insert (insert), update (update), and sort (sort).
Each command initiates the corresponding action in the ListView-assuming that you want to add a sort to the ListView, it is only necessary to place a button in the LayoutTemplate (the demo sample in Figure 8 uses LinkButton). Set its CommandName property to sort, and set CommandArgument to the name of the column you want the data source to sort. In Figure 8 . I've changed the static header link for each column in the grid to a clickthrough link that you can click to request the ListView to sort the data by that column. Figure 8 Sorting in ListView copy code
<asp:listview id= "_moviesgrid" runat= "Server" datakeynames= "movie_id"
Datasourceid= "_moviesdatasource" >
<LayoutTemplate>
<div class= "Prettygrid" >
<table cellpadding= "0" cellspacing= "0" summary= "" >
<thead>
<tr>
<th scope= "Col" >
<asp:linkbutton id= "_movieidsortlink"
Commandname= "Sort" commandargument= "movie_id"
runat= "Server" >ID</asp:LinkButton>
</th>
<th scope= "Col" >
<asp:linkbutton id= "_titlesortlink"
Commandname= "Sort" commandargument= "title"
runat= "Server" >Title</asp:LinkButton>
</th>
<th scope= "Col" >
<asp:linkbutton id= "_releasedatesortlink"
Commandname= "Sort" commandargument= "Release_date"
runat= "Server" >release date</asp:linkbutton>
</th>
</tr>
</thead>
<!--...-->
</LayoutTemplate>
</asp:ListView>
You can add a command button to start edit mode, delete a row, or insert a new row in the data set. The process is essentially the same as other template-based data-bound controls, such as the FormView and GridView, which are not mentioned here.
The last major feature of a grouped ListView is the ability to group data into subsets, much like the functionality provided by the DataList control.
DataList is a table-formatted control. It renders a single row of data in each cell of the rendered data table.
You can control how many rows of the underlying dataset are grouped into a single table row by setting the RepeatColumns property.
Because the ListView is not limited to rendering tables. So it requires a more general way to specify the group of items that will be presented together. And that's the way GroupTemplate offers it. Figure 9 shows the relationship between the LayoutTemplate, GroupTemplate, and ItemTemplate elements in the ListView. GroupTemplate can specify peripheral HTML for every n elements in the underlying dataset, where the value of n is specified by the ListView's GroupItemCount property. Figure 9 template in ListView (click the image for a larger view) when using GroupTemplate in a ListView, you do not need to specify the Itemplaceholder ID in the LayoutTemplate Control-the control now needs to be inside GroupTemplate. Instead, you need to specify the control with the Groupplaceholder ID in the LayoutTemplate (the ability to change the control ID by setting the Groupplaceholderid property of the ListView) to indicate which bit to use for every n items in the underlying data set To inject grouptemplate content.
For example, the ListView in figure shows how to define GroupTemplate as a search row and set ItemTemplate to layout cells only. To display four movies from a database in each row of the table. The results are as seen in figure one. Figure ten defining Rows with GroupTemplate copy code
<asp:listview id= "_grouplistview" runat= "Server"
Datakeynames= "movie_id" datasourceid= "_moviesdatasource"
Groupitemcount= "4" >
<GroupTemplate>
<tr>
<asp:placeholder runat= "Server" id= "Itemplaceholder"/>
</tr>
</GroupTemplate>
<LayoutTemplate>
<table>
<asp:placeholder id= "Groupplaceholder" runat= "Server"/>
</table>
</LayoutTemplate>
<ItemTemplate>
<td>
MOVIE_ID:
<asp:label id= "_movie_idlabel" runat= "Server"
Text= ' <%# Eval ("movie_id")%> '/> <br/>
Title
<asp:label id= "_titlelabel" runat= "Server"
Text= ' <%# Eval ("title")%> '/> <br/>
Release_date:
<asp:label id= "_release_datelabel" runat= "Server"
Text= ' <%# Eval ("Release_date", "{0:d}")%> '/> <br/>
<br/>
</td>
</ItemTemplate>
</asp:ListView>
Figure 11
grouptemplate rows in the results Web page(Click the image for a larger view) this is similar to the work done with DataList, but thanks to the ListView, it is easy to add paging and sorting functions as seen in the previous grid rendering. The use of DataList to complete these tasks is complex.
The download code for this article includes a demo sample that implements the paging and sorting functionality for your reference.
Start running the ListView you might want to try the ListView control by using the designer in Visual Studio 2008, which provides five different layouts for you to choose from: Grid, tile, bulleted list, flow, and single row. You can see the various layout options available at a high speed--but the real power of the ListView is your control of the HTML it renders, so you are very likely to build your own layouttemplate in the actual project. Did you finally decide to use the ListView every time you encounter data binding? Although it may be a bit overdone--but I'm glad to know you're going to do it. I think I'll be doing a lot of other research on this flexible data-bound control in the future.
Please send the questions and comments you would like to ask Fritz to [email protected].
Fritz Onionis one of the founders of Pluralsight (a Microsoft. NET training Provider), responsible for hosting the title of Web Development course. Fritz this is
author of "Essential ASP." and "Essential ASP. NET 2.0" .
To understand this author, please log in to Pluralsight.com/fritz.
ListView usage method (ASP)