前些时候学习asp.net三层架构的时候,想把集合绑定到listview上。但是怎么也想不出来,很是苦恼网上貌似也找不到比较合适的答案,今天心血来潮问了下身边的同事。通过同事的细心讲解我才恍然大悟原来控件还能这么用,真是大开眼界.
1.假设我有一个pojo类如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace studentmanage
{
public class Student
{
public string name { set;get;}
public string password { set; get; }
}
}
2.假设我通过3层架构查询出了许多数据,这里我就随便拼凑几条单做是查询出来的数据
Student stu1= new Student();
List<Student> all = new List<Student>();
stu1.name = "潘玮柏";
stu1.password = "123456";
all.Add(stu1);
Student stu2= new Student();
stu2.name = "蔡依林";
stu2.password = "123456";
all.Add(stu2);
3.下面就轮到listview出场了,我们把集合绑定上去就可以了
ListView1.DataSource = all;
ListView1.DataBind();
这里的ListView1指的是listview控件的id,当然了使用其他数据控件也是同样的道理
4.分页显示数据
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="studentmanage.index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
table
{
border-collapse: collapse;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ListView ID="ListView1" runat="server" ItemContainerID= "ItemPlaceHolder">
<LayoutTemplate>
<table border="1" width="500" bordercolor="#00ff00" border-collapse="collapse">
<thead>
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
</thead>
<tbody>
<asp:PlaceHolder runat="server" ID="ItemPlaceHolder"></asp:PlaceHolder>
</tbody>
</table>
<asp:DataPager runat="server" ID="ContactsDataPager" PageSize="1">
<Fields>
<asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true"
FirstPageText="首页" LastPageText="尾页"
NextPageText="下一页" PreviousPageText="上一页"/>
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("name")%></td>
<td><%#Eval("password")%></td>
</tr>
</ItemTemplate>
</asp:ListView>
</form>
</body>
</html>
这里需要注意<%#Eval("name")%>和<%#Eval("password")%>里写的name和password代表的是对象名。有时可能是表的列名。