ListView usage method (ASP)

Source: Internet
Author: User

The unique data-bound control you will need to use. Fritz Onion


code Download location: Extremeaspnet2008_03.exe (192 KB)
Browse the Code Online

Folder ListView Basics
ListView and CSS
Pagination
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? After all, we have more than 10 controls to choose from when displaying data collection, including a DataGrid that is no longer in use, a new and improved GridView, a reliable and simple Repeater, unique and flexible DataList, convenient FormView and its 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, and you'll need to place the repeated HTML content in ItemTemplate in the bound dataset. 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, if you want the ListView to be rendered as a table, you can include top <table> and <thead> elements in LayoutTemplate, leaving the row and cell rendering to ItemTemplate, such as Figure 1What you see (in this demo sample, the bound data source displays a simple table that includes the movie title and the release date). Figure 2Shows 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, where I want to inject the 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 with the server-side table row instead of the PlaceHolder control to achieve the same effect: Copy the 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>
Typically, for the following two reasons, I prefer to use a generic PlaceHolder control. The first reason is that the names match very well. Also, 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 Figure 3See): Figure 3 same list, different formats(Click the image for a larger view) to copy the code
   <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 of the default controls render inline styles, or it is difficult to associate CSS classes with their HTML output parts. 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 that developers manually pre-design a particular page, often including 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 errors that developers have experienced, applying style attributes to the grid, viewing the source of the page to understand exactly where the style is placed, and repeating the experiment until the grid can be rendered as required. With the ListView, you don't have to do this work anymore, because you can now control the layout and content. For example, if the form provided to you needs to follow Figure 4The way you see it, and use a design that consists of. htm and. css files, such as Figure 5As seen in the. Figure 5 HTML and CSS for the Table

HTMLCopy 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 create a ListView that can be rendered precisely according to HTML/CSS combination requirements by selecting the appropriate part from the HTML and placing it in the appropriate template, 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 DataPager in the layouttemplate of the ListView, they establish an intrinsic connection. 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 this particular case, Numericpagerfield accurately shows the interface I want-a series of numbers displayed as hyperlinks that can 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 (now the ListView is the only control that implements the interface), as seen in 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 ListView, DataPager, and DataSource(Click the image for a larger view) when you are ready to page out, the ListView query DataSource to see if it supports paging, assuming support, and whether it can return the total number of rows. Assuming that 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 the associated DataPager control will subscribe to the event and initialize the fields required to display the paging interface using the total number of rows. 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, which can radically change how DataPager works. By setting the Querystringfield property to some string (such as Pagenum), you request DataPager to send an HTTP GET request in response to a user clicking on the page number, and the requested page number is sent through the query string parameter of the string you specified. Instead of sending it 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. Note that if you switch to such a get communication pattern, the POST postback hook mechanism used by the ASP. NET AJAX UpdatePanel control will not intercept the paging request and will turn it into an asynchronous postback: Copy the 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 a SqlDataSource control, only if it is set to DataSet mode when the page is capable of working properly, which means that the entire result set needs to be loaded into memory to run the paging. 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, the CommandName property is set to one of the following seven specific command strings in its template, which can be identified: Cancel, delete (delete), select (select), Edit, insert (insert), update (update) and sort (sort). Each command will initiate the corresponding action in the ListView-assuming that you want to add to the ListView, you just need to place a button in the LayoutTemplate ( Figure 8LinkButton in the Demo sample), set its CommandName property to sort, and set CommandArgument to the name of the column that you want the data source to sort. In Figure 8, I 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 for starting edit mode, deleting rows, or inserting new rows into a dataset. 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 that 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 the table, it requires a more general way of specifying the group of items that will be presented together, which is exactly how GroupTemplate provides it. Figure 9Shows the relationships between 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 templates in the ListView(Click the image for a larger view) when you use GroupTemplate in a ListView, you do not need to specify a control with a itemplaceholder ID in LayoutTemplate--the control now needs to be located in the GroupTemplate Within 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. Like what Figure TenThe ListView in shows how to display four movies from a database in each row of a table by defining GroupTemplate as a search row and setting ItemTemplate to layout cells only. Results such as Figure OneWhat you see. 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 with the ListView, it is as easy to join as the grid rendering as previously seen, and it is complex to use DataList to complete these tasks. 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 WEB development topics. Fritz is author of Essential ASP and Essential ASP. NET 2.0 . To learn about this author, please log in to Pluralsight.com/fritz.

ListView usage method (ASP)

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.