在ASP.NET 3.5中使用新的ListView控件

ASP.NET中新的ListView控件为显示和CURD数据库操作提供了基于模板的布局,使之成为一项极好的方式,建立以数据为中心的Web应用程序。

当你编写以用户为中心的应用程序时,总需要某种形式的数据集,起码来说,你需要从一个数据源如关系数据库或XML文件检索数据,在显示给用户之前先要进行格式化,尽管ASP.NET之前的版本就提供了以数据为中心的显示控件如GridView,这些控件缺乏专业Web开发人员需要的可自定义和可扩展特性,为了解决这个问题,ASP.NET3.5提供了一个新的控件ListView,它提供了非常优秀的自定义和扩展特性,使用这些特性,你可以以任何格式显示数据,使用模板和样式,同时用最少的代码执行CURD(创建、读取、更新、删除)操作。

本文主要集中于使用新的ListView控件时数据访问步骤,同时还包括高级特性如编辑数据和处理事件。

ListView控件入门

ASP.NET提供的大部分数据绑定控件都是使用额外的标记自动封装显示数据,举例来说,GridView控件在一个HTML表格(

),虽然你可以使用TemplateField组件自定义GridView的外观,但GridView的输出仍然是限制在一个table组件中的,但有时候你想要完全控制由数据绑定控件产生的HTML标记的外观,这正是ListView控件的优势,ListView控件不是使用额外的标记来封装它的输出内容,而是靠你指定的精确的HTML描述,使用ListView控件内置的模板就可以指定精确的标记,表1列出了ListView控件支持的模板。

模板

用途

AlternatingItemTemplate

交替项目模板

用不同的标记显示交替的项目,便于查看者区别连续不断的项目

EditItemTemplate

编辑项目模板

控制编辑时的项目显示

EmptyDataTemplate

空数据模板

控制ListView数据源返回空数据时的显示

EmptyItemTemplate

空项目模板

控制空项目的显示

GroupSeparatorTemplate

组分隔模板

控制项目组内容的显示

GroupTemplate

组模板

为内容指定一个容器对象,如一个表行、div或span组件

InsertItemTemplate

插入项目模板

用户插入项目时为其指定内容

ItemSeparatorTemplate

项目分隔模板

控制项目之间内容的显示

ItemTemplate

项目模板

控制项目内容的显示

LayoutTemplate

布局模板

指定定义容器对象的根组件,如一个table、div或span组件,它们包装ItemTemplate或GroupTemplate定义的内容。

SelectedItemTemplate

已选择项目模板

指定当前选中的项目内容的显示

最关键的两个模板是LayoutTemplate和ItemTemplate,正如名字暗示的那样,LayoutTemplate为ListView控件指定了总的标记,而ItemTemplate指定的标记用于显示每个绑定的记录,例如:下面的代码显示了在ListView中由HTML table控制的一串项目。

<listview id="..." runat="server" datasourceid="..."><br><layouttemplate><br><table> <br><tr runat="server" id="itemPlaceholder"></tr> <br> </table> <br></layouttemplate><br><itemtemplate><br><tr> <br><td></td> <br> </tr> <br></itemtemplate><br></listview>

在前面的代码中,LayoutTemplate标记内的

你已经看到LisView控件支持的多个模板了,下一步是要创建一个简单的web站点,名字就叫做ListViewExample(你可以从http://assets.devx.com/sourcecode/38579_tt_mainsource.zip下载该站点的示例代码),创建好web站点后,选择Web站点?添加新项目,添加一个新的ASP.NET页面,名字命名为SimpleListView.aspx(见清单1),这个页面将使用ListView控件从AdventureWorks示例数据库中的Product表显示产品数据。

清单1.ListView控件示例清单




<link rel="Stylesheet" type="text/css" href="StyleSheet.css">
Simple Data Binding Example using ListView control




<listview runat="server" id="productsView"></listview>DataSourceID="productSource" DataKeyNames="ProductID">
<layouttemplate><br><table cellpadding="2" runat="server" id="tblProducts"></table>style="width:460px"&gt; <br><tr runat="server" id="itemPlaceholder"><br></tr> <br></layouttemplate>

<datapager runat="server" id="DataPager" pagesize="3"><br><fields><br><numericpagerfield buttoncount="10"></numericpagerfield>PreviousPageText="" /&gt; <br></fields><br></datapager>

<itemtemplate><br><tr id="row" style="height:72px" runat="server"> <br><td valign="top" class="ProductInfo"> <br>Product ID : <label id="lblProductID" runat="server"></label>Text='' /&gt; <br><br><br>Name : <label id="lblName" runat="server"></label>Text='' /&gt; <br><br><br>Product Number : <label id="lblProductNumber"></label>runat="server" Text='' /&gt; <br> </td> <br> </tr> <br></itemtemplate>
<itemseparatortemplate><br><tr id="separator" style="height:10px" runat="server"> <br><td>-------------------------------------------------------- <br>------------------</td> <br> </tr> <br></itemseparatortemplate>
<emptydatatemplate><br>There are no products! <br></emptydatatemplate>

<sqldatasource id="productSource" runat="server"></sqldatasource>DataSourceMode="DataSet"
ConnectionString=""
SelectCommand="SELECT ProductID,Name,ProductNumber,
Color,ListPrice FROM Production.Product">




在清单1中,SqlDataSource通过设置ConnectionString 和SelectCommand 属性控制从AdventureWorks数据库的Product表中检索数据,ConnectionString属性通过一个ASP.NET表达式从web.config文件获取连接字符串,在我的测试机上,连接字符串定义在web.config中,如:

<connectionstrings><br><add name="AdventureWorks"></add>connectionString="server=localhost;uid=sa; <br>pwd=thiru;database=AdventureWorks;"/&gt; <br></connectionstrings>

设置好SqlDataSource属性后,下一步是通过ListView控件显示数据,下面是在LayoutTemplate模板中的标记:

<layouttemplate><br><table cellpadding="2" runat="server" id="tblProducts"></table>style="width:460px"&gt; <br><tr runat="server" id="itemPlaceholder"><br></tr> <br></layouttemplate>


<datapager runat="server" id="DataPager" pagesize="3"><br><fields><br><numericpagerfield buttoncount="10"></numericpagerfield>PreviousPageText="" /&gt; <br></fields><br></datapager>

LayoutTemplate模板定义了ListView控件输出内容的容器,除了在ListView控件顶层定义了table外,LayoutTemplate模板还定义了<datapager>,它为ListView控件提供了分页功能,DataPager让你可以为任何数据绑定控件实现IpageableItemContainer进行数据分页并显示导航控制。</datapager>

有两种方法使数据分页(DataPager)和数据绑定(data-bound)联合使用:

1、设置DataPager 的PagedControlID属性为data-bound的名字。
2、将DataPager置于data-bound层次体系之下,对于ListView控件,你可以将DataPager置于LayoutTemplate组件内。

设置DataPager的PageSize属性,它控制每页显示的数据行数,你也可以在页面提交到服务器时通过设置QueryStringField属性实现。

在DataPager内,你指定NumericPageField模板,它可以让用户输入一个页号,然后按照页号进行跳转,如:

<numericpagerfield buttoncount="10"></numericpagerfield>PreviousPageText="NextPageText="-->" />

ItemTemplate组件为每个记录的明细提供了标记。图1显示了在浏览器中导航到该页面的输出。

在ASP.NET 3.5中使用新的ListView控件

点击查看大图


图1.ListView示例:通过数据绑定ListView控件到SqlDataSource控件检索Product表中部分数据产生的输出

正如你所看到的,使用ListView控件显示数据相对要直接得多,但你还可以让用户在ListView中直接编辑数据,添加一个新页面ListViewEditExample.aspx,它的代码如清单2所示。

清单2.编辑ListView


<script runat="server"> <br />void deptsView_ItemUpdated(object sender, <br />ListViewUpdatedEventArgs e) <br />{ <br />lblResult.Text = e.AffectedRows.ToString() + <br />" row(s) successfully updated"; <br />}</p> <p>void deptsView_PagePropertiesChanged(object sender, EventArgs e) <br />{ <br />//Set the text to empty when navigating to a different page <br />lblResult.Text = ""; <br />} <br /></script>


<link rel="Stylesheet" type="text/css" href="StyleSheet.css">
Editing Data using ListView Control




<listview id="ContactsListView" datasourceid="deptSource"></listview>DataKeyNames="DepartmentID" runat="server"
OnItemUpdated="deptsView_ItemUpdated"
OnPagePropertiesChanged="deptsView_PagePropertiesChanged">
<layouttemplate><br><table cellpadding="2" width="640px" border="1"></table>runat="server" id="tblProducts"&gt; <br><tr id="row1" runat="server" class="header"> <br><th id="header2" runat="server">Name</th> <br><th id="header3" runat="server">Group Name</th> <br><th id="header1" runat="server">Action</th> <br> </tr> <br><tr runat="server" id="itemPlaceholder"></tr> <br><br><datapager runat="server" id="deptsDataPager"></datapager>PageSize="3"&gt; <br><fields><br><nextpreviouspagerfield showfirstpagebutton="True"></nextpreviouspagerfield>ShowLastPageButton="True" FirstPageText="|LastPageText=" &gt;&gt;|" NextPageText=" &gt; " <br>PreviousPageText=" <br></fields><br><br></layouttemplate>
<itemtemplate><br><tr id="row2" runat="server"> <br><td> <br><label id="lblName" runat="Server"></label>Text='' /&gt; <br> </td> <br><td valign="top"> <br><label id="lblGroupName" runat="Server"></label>Text='' /&gt; <br> </td> <br><td> <br><linkbutton id="btnEdit" runat="Server" text="Edit"></linkbutton>CommandName="Edit" /&gt; <br> </td> <br> </tr> <br></itemtemplate>
<edititemtemplate><br><tr style="background-color: #ADD8E6"> <br><td> <br><textbox id="txtName" runat="server"></textbox>Text='' <br>MaxLength="50" /&gt;<br><br> </td> <br><td> <br><textbox id="txtGroupName" runat="server" text='&lt;%# &lt;br /&gt;Bind("GroupName") %&gt;' maxlength="50"></textbox><br><br> </td> <br><td> <br><linkbutton id="btnUpdate" runat="server"></linkbutton>CommandName="Update" Text="Update" /&gt; <br><linkbutton id="btnCancel" runat="server"></linkbutton>CommandName="Cancel" Text="Cancel" /&gt; <br> </td> <br> </tr> <br></edititemtemplate>

<sqldatasource id="deptSource" runat="server"></sqldatasource>ConnectionString=""
SelectCommand="SELECT [DepartmentID],[Name],[GroupName] FROM
HumanResources.Department" UpdateCommand="UPDATE
HumanResources.Department SET Name = @Name,
GroupName = @GroupName WHERE DepartmentID = @DepartmentID">




Font-Bold="true" />



清单2的代码说明了如何使用EditItemTemplate组件在编辑模式下生成内容,然后通过SqlDataSource更新数据库

首先,你设置SqlDataSource的UpdateCommand属性,这样SQL语句就会用由用户指定的最新值执行数据库更新操作。

<sqldatasource id="deptSource" runat="server"></sqldatasource>ConnectionString=""
SelectCommand="SELECT [DepartmentID],[Name],[GroupName] FROM
HumanResources.Department" UpdateCommand="UPDATE
HumanResources.Department SET Name = @Name,
GroupName = @GroupName WHERE DepartmentID = @DepartmentID">

接下来,在ItemTemplate组件中,指定编辑项目的连接用户:

<itemtemplate><br>---- <br>---- <br><linkbutton id="btnEdit" runat="Server" text="Edit"></linkbutton>CommandName="Edit" /&gt; <br><br><br></itemtemplate>

然后,指定EditItemTemplate声明用户输入更新的部门名称或组名的文本框,以及提交或取消当前操作的用户连接。

<edititemtemplate><br><tr style="background-color: #ADD8E6"> <br><td> <br><textbox id="txtName" runat="server"></textbox>Text='' <br>MaxLength="50" /&gt;<br><br> </td> <br><td> <br><textbox id="txtGroupName" runat="server" text='&lt;%# &lt;br /&gt;Bind("GroupName") %&gt;' maxlength="50"></textbox><br><br> </td> <br><td> <br><linkbutton id="btnUpdate" runat="server"></linkbutton>CommandName="Update" Text="Update" /&gt; <br><linkbutton id="btnCancel" runat="server"></linkbutton>CommandName="Cancel" Text="Cancel" /&gt; <br> </td> <br> </tr> <br></edititemtemplate>

这里通过CommandName属性定义的LinkButton的行为,如表2所示。

表2. LinkButton CommandName属性值:列出了ListView控件支持的CommandName属性值

描述

Cancel

取消当前操作

Delete

从数据源删除当前选中的项目

Edit

切换ListView到编辑模式,显示EditItemTemplate组件中指定的内容

Insert

作为一条新记录将数据保存到数据源

Update

用指定的值更新数据源

在更新结束后,ListView控件**一个OnItemUpdated事件,你可以用它向用户提供执行的状态,在清单2的代码中,ListView控件处理两个事件:

1、OnItemUpdated:正如名字所暗示的那样,这个事件允许你在更新操作完毕后执行一个自定义的程序,在前面的代码中,这个事件被用于通知用户影响的记录条数。
2、OnPagePropertiesChanged:当页面属性发生改变时ListView控件**这个事件,前面代码中使用这个事件清除了在lable标记包括的文本。

如果你导航到该页面,你会看到如图2所示的页面:

在ASP.NET 3.5中使用新的ListView控件

点击查看大图

图2.在运转中编辑ListView:配置ListView控件为每条记录显示一个编辑连接,点击编辑连接切换到编辑模式

当你点击了编辑(Edit)超链接后,ListView控件使用EditItemTemplate显示文本框,用户就可以编辑文本框中的内容了,如图3所示:

在ASP.NET 3.5中使用新的ListView控件

点击查看大图

图3.编辑模式:在编辑模式下,EditItemTemplate组件产生文本框,用户可以在这里输入要更新的值

注意在编辑模式下右边的更新(Update)和取消(Cancel)链接,当你点更新链接就会将所做的改变保存到数据库中,代码使用了OnItemUpdated事件显示更新操作所影响的行数,如图4所示:

在ASP.NET 3.5中使用新的ListView控件

点击查看大图

图4.影响的记录:更新结束时,显示更新操作影响的数据行数

以上就是ListView的全部关键特性了,同时你也看到了一个使用ListView控件的简单以数据驱动的示例web页面,以及更复杂的更新功能,最后,描述了如何使用ListView控件产生的事件,正如你看到的,ListView控件扩展了运行时自定义的特性,更加适合你的需要。

注:本文示例代码下载地址http://assets.devx.com/sourcecode/38579_tt_mainsource.zip