Asp.Net ListView 控件的使用

     Asp.Net ListView 数据绑定控件是在Asp.Net 3.5中引入的,在此之前我们已经拥有了n多同类的控件了。那么我们还有必要再增加这类控件吗?答案是Yes!它为你提供了强大的可高度自定义外观功能,使用它你几乎可以扔掉其他的数据绑定控件了。

ListView 包含大量的模板,使用这些模板我们可以很方便地显示、编辑、插入数据,也可以对数进行分组,设置选中一行数据或如数据为空时的显示方式等。主要的模板有: 

·LayoutTemplate  ·ItemTemplate  ·AlternatingItemTemplate  ·SelectedItemTemplate  ·EmptyItemTemplate  ·EmptyDataTemplate

·ItemSeparatorTemplate  ·GroupTemplate ·GroupSeparatorTemplate  ·EditItemTemplate  ·InsertItemTemplate

 

一、显示数据

    显示数据要用到两个关键模板分别是LayoutTemplate 和 ItemTemplate,其中LayoutTemplate用于控制数据的外观呈现,而ItemTemplate则用于提供数据集中的每一行数据。ListView将用ItemTemplate中的数据填充到LayoutTemplate中的占位符位置。

 

    先创建一个ADO.NET 实体数据模型(使用Northwind 示例数据库),用EntityDataSource 配置为Products数据集。

 

<asp:EntityDataSource ID="EntityDataSource1" runat="server"
ConnectionString
="name=NorthwindEntities"
DefaultContainerName
="NorthwindEntities" EnableFlattening="False"
EntitySetName
="Products">
</asp:EntityDataSource>

 

 

   

    接着拖放一个ListView到设计窗口中设置其DataSourceID="EntityDataSource1",并在窗口中修改成如下的代码:

 

<asp:ListView ID="ListView1" runat="server" DataSourceID="EntityDataSource1" ItemContainerID= "ItemPlaceHolder ">
<LayoutTemplate>
<table border="2">
<thead>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>UnitPrice</th>
</tr>
</thead>
<tbody>
<asp:PlaceHolder runat ="server" ID="ItemPlaceHolder"></asp:PlaceHolder>
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductID")%></td>
<td><%# Eval("ProductName")%></td>
<td><%# Eval("UnitPrice")%></td>
</tr>
</ItemTemplate>
</asp:ListView>

 

 

   

     代码中LayoutTemplate模板我们定义了一个HTML Table控件,请注意其中的 一行:

     <asp:PlaceHolder  runat ="server" ID="ItemPlaceHolder"></asp:PlaceHolder>

服务器控件PlaceHolder 实际上起到了占位符的作用,其中" ItemContainerID= "ItemPlaceHolder "属性是关键,它指示ListView在ID="ItemPlaceHolder" 的控件的位置进行填充数据。

ItemTemplate  模板我们定义了一个数据行共3个数据单元,这些数据将填充在ID="ItemPlaceHolder"的控件位置上。图(1)是运行的结果

          

posted @ 2010-08-09 21:41  行之者  阅读(7349)  评论(1编辑  收藏  举报