知识点:掌握 DataList 控件呈现数据的方法; 掌握 Repeater 控件呈现数据的方法;掌握处理 Repeater 控件中的按钮事件。
1、 使用 DataList 控件呈现数据
在用 ASP.NET 开发 Web 应用程序时,DataList 是非常重要的数据绑定控件。DataList 控件 可用于创建模板化的列表数据,如果重复结构比较复杂,那么建议使用 DataList 和 Repeater 控件,因为 GridView 控件比较适合显示多行多列的表格类数据。
示例练习1:DataList控件的使用
要求:制作一个车型展示页面,使用DataList控件。
前提:在【ASP.NET第八课】的基础之上完成。
第一步,添加Web窗体:在VS中打开已有项目【WebApplication7】,右键单击项目名称【WebApplication7】,依次点击【添加】→【Web窗体】,将窗体命名为CarList,然后单击【确定】。
第二步,添加DataList控件:在默认打开的CarList.aspx文件中,从工具箱拖放一个DataList控件到适合的位置。
第三步,绑定数据源:打开CarList.aspx文件,切换到【拆分】视图。
①选中DataList控件后,点击右上角,在弹出的【DataList任务】中,点击【选择数据源】,然后点击下拉箭头,点击【<新建数据源…>】
②在弹出的【数据源配制向导】窗体中,选择默认应用程序从哪里获取数据?【数据库】,为数据源指定ID,使用默认名称,然后点击【确定】
③在弹出的【配制数据源】窗口中,点击【新建连接】按钮
④在弹出的【添加连接】窗口中,输入服务器名,这个一般可以使用英文的点即可。如果无法使用英文点,则需要写数据库按照时的服务器名。然后再下面点选要连接的数据库名称,最后点击【确定】
⑤此时会自动填写一行代码,直接点击【下一步】
⑥单击【下一步】
⑦在【配置数据源】窗口中,设置想要查询的数据,我们这查询Scar表的所有列,然后点击【下一步】
⑧可以点击【测试查询】看一下结果,最后点击【完成】按钮。
⑨注意分析查看此时源代码文件
代码分析:DataList 的模板类型包括:ItemTemplate 用于显示项,AlternatingItemTemplate 用于显 示交替项,EditItemTemplate 用于显示编辑项,同时也支持 HeaderTemplate、FooterTemplate 等模板,这些模板的作用与 GridView 控件中模板列的模板相同。另外,DataList 还支持间隔项 模板 SeparatorTemplate,用于在两个项之间显示。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CarList.aspx.cs" Inherits="WebApplication7.CarList" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DataList—王迪</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" DataKeyField="CarId" DataSourceID="SqlDataSource1">
<ItemTemplate>
CarId:
<asp:Label ID="CarIdLabel" runat="server" Text='<%# Eval("CarId") %>' />
<br />
CarName:
<asp:Label ID="CarNameLabel" runat="server" Text='<%# Eval("CarName") %>' />
<br />
BrandId:
<asp:Label ID="BrandIdLabel" runat="server" Text='<%# Eval("BrandId") %>' />
<br />
Picture:
<asp:Label ID="PictureLabel" runat="server" Text='<%# Eval("Picture") %>' />
<br />
OfficialPrice:
<asp:Label ID="OfficialPriceLabel" runat="server" Text='<%# Eval("OfficialPrice") %>' />
<br />
Click:
<asp:Label ID="ClickLabel" runat="server" Text='<%# Eval("Click") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarSYSConnectionString %>" SelectCommand="SELECT * FROM [Scar]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
第四步,运行测试:在CarList.aspx页面单击鼠标右键,然后点击【在浏览器中查看】
我们看到数据源中的所有数据显示出来,但是一行只显示一列数据。
观察一下页面源代码:DataList控件默认输出是一个table表格。
第五步,设置列数:给DataList控件添加一个RepeatColumns属性。
第六步,设计样式:
①先制作一个样式出来,写div+css实现图中效果。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CarList.aspx.cs" Inherits="WebApplication7.CarList" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DataList—王迪</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#CarListShow{
width:350px;
height:180px;
border:1px solid black;
}
h3{
height:30px;
line-height:30px;
text-align:center;
background-color:bisque;
}
#CarListShow img{
width:150px;
height:150px;
display:block;
float:left;
}
#CarListShow ul{
border-left:1px solid black;
float:left;
list-style-type:none;
margin-left:10px;
border-left:1px solid black;
width:189px;
}
#CarListShow ul li{
height:50px;
line-height:50px;
text-align:left;
}
.li1{
border-bottom:1px solid black;
border-top:1px solid black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="CarListShow">
<h3>汽车名称</h3>
<img src="images/ada31.jpg" />
<ul>
<li>编号:</li>
<li class="li1">官方价格:</li>
<li>点击量:</li>
</ul>
</div>
<div>
<asp:DataList ID="DataList1" RepeatColumns="3" runat="server" DataKeyField="CarId" DataSourceID="SqlDataSource1">
<ItemTemplate>
CarId:
<asp:Label ID="CarIdLabel" runat="server" Text='<%# Eval("CarId") %>' />
<br />
CarName:
<asp:Label ID="CarNameLabel" runat="server" Text='<%# Eval("CarName") %>' />
<br />
BrandId:
<asp:Label ID="BrandIdLabel" runat="server" Text='<%# Eval("BrandId") %>' />
<br />
Picture:
<asp:Label ID="PictureLabel" runat="server" Text='<%# Eval("Picture") %>' />
<br />
OfficialPrice:
<asp:Label ID="OfficialPriceLabel" runat="server" Text='<%# Eval("OfficialPrice") %>' />
<br />
Click:
<asp:Label ID="ClickLabel" runat="server" Text='<%# Eval("Click") %>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarSYSConnectionString %>" SelectCommand="SELECT * FROM [Scar]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
②将写好的样式,套用到DataList控件中。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CarList.aspx.cs" Inherits="WebApplication7.CarList" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DataList—王迪</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#CarListShow{
width:350px;
height:180px;
border:1px solid black;
}
h3{
height:30px;
line-height:30px;
text-align:center;
background-color:bisque;
}
#CarListShow img{
width:150px;
height:150px;
display:block;
float:left;
}
#CarListShow ul{
border-left:1px solid black;
float:left;
list-style-type:none;
margin-left:10px;
border-left:1px solid black;
width:189px;
}
#CarListShow ul li{
height:50px;
line-height:50px;
text-align:left;
}
.li1{
border-bottom:1px solid black;
border-top:1px solid black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" RepeatColumns="3" runat="server" DataKeyField="CarId" DataSourceID="SqlDataSource1">
<ItemTemplate>
<div id="CarListShow">
<h3><%# Eval("CarName") %></h3>
<img src="images/<%# Eval("Picture") %>" />
<ul>
<li>编号:<%# Eval("CarId") %></li>
<li class="li1">官方价格:<%# Eval("OfficialPrice") %></li>
<li>点击量:<%# Eval("Click") %></li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarSYSConnectionString %>" SelectCommand="SELECT * FROM [Scar]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
运行测试:
细节调整:如每个产品之间增加一些间隔,可以设置div的margin属性,如margin:0px 10px 20px 0px;
2、Repeater 控件
Repeater 控件专门用于精确内容的显示,它也是基于模板的方式,不过它不会自动生成任 何用于布局的代码。Repeater 控件甚至没有一个默认的外观,它完全是通过模板来控制。而且也只能通过源代码视图进行模板的编辑。
2.1 使用 Repeater 控件呈现数据
GridView 和 DataList 自动生成<table>标签,但是 Repeater 控件不会自动生成任何 HTML 标签,所以带来了效率上的提升,也使精确展示内容成为可能。
示例练习2:使用 Repeater 控件呈现数据
要求:在当前项目中,新添加一个Web窗体,并使用 Repeater 控件呈现车型列数据。
第一步,添加Web窗体:右键单击项目名称【WebApplication7】,依次点击【添加】→【Web窗体】,将窗体命名为CarListRepeater,然后单击【确定】。
第二步,添加Repeater控件:在默认打开的CarListRepeater.aspx文件中,从工具箱拖放一个Repeater控件到适合的位置。
第三步,绑定数据源:在CarListRepeater.aspx文件中,单击鼠标右键,然后点击【查看代码】,打开后置代码文件CarListRepeater.aspx.cs
//声明一个方法,绑定数据源
public void BindRepeater()
{
this.Repeater1.DataSource = DBHelper.getDataSet("select * from Scar").Tables[0];
this.Repeater1.DataBind();
}
第四步,调用绑定方法:在“CarListRepeater.aspx.cs”文件的Page_Load方法里,调用刚才写的方法。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
}
}
第五步,运行测试:直接将“CarListRepeater.aspx”文件在浏览器中运行测试
页面上似乎没有内容,因为Repeater控件不会自动生成任何用于布局的代码。想要将数据显示出来,我们需要继续操作。
第六步,编辑Repeater控件:回到CarListRepeater.aspx文件,将视图切换到【拆分】模式,选中Repeater控件,注意观察Repeater控件不同于DataList控件,没有编辑模板功能。只能在“源视图里编辑控件模板”。当我们在Repeater控件标签之间,输入尖括号<,会自动提示可以使用标签:
模板属性 | 说明 | 标签之间内容出现次数 |
AlternatingItemTemplate | 包含要为数据源中每个数据项都要呈现一次的 HTML 元素和控件。 通常,可以使用此模板为交替项创建不同的外观,例如指定一种与在 ItemTemplate 中指定的颜色不同的背景色。 | itemtemplate轮换出现 |
FooterTemplate | 包含在列表的结束处呈现的文本和控件。 | 标签之间的内容只出现一次。 |
HeaderTemplate | 包含在列表的开始处呈现的文本和控件。 | 标签之间的内容只出现一次。 |
ItemTemplate | 包含要为数据源中每个数据项都要呈现一次的 HTML 元素和控件。 | 标签之间的内容循环出现 |
SeparatorTemplate | 包含在每项之间呈现的元素。典型的示例可能是一条直线(使用 hr 元素)。 | 间隔的内容 |
①简单编写模板:这里使用HeaderTemplate、ItemTemplate和FooterTemplate
运行测试:注意观察页面,总结规律。Repeater控件默认一行展示,除了用户自定义的模板,不会自动生成任何用于布局 的代码。
②优化模板:比如增加换行标签
③呈现数据:如呈现数据源里的车型名称,使用<%#Eval("CarName") %> 获取
④编写完整样式:呈现数据、美化样式
完整代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CarListRepeater.aspx.cs" Inherits="WebApplication7.CarListRepeater" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Repeater—王迪</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#CarList{
margin:10px auto;
width:660px;
}
dl{
float:left;
width:200px;
height:300px;
margin-left:20px;
}
#CarList img{
width:200px;
height:200px;
}
#CarList .dtPrice{
color:red;
float:left;
width:100px;
height:30px;
}
#CarList .dtClick{
color:dimgray;
float:right;
text-align:right;
width:100px;
height:30px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<%--<HeaderTemplate>车型展示——头部<br /></HeaderTemplate>--%>
<ItemTemplate>
<div id="CarList">
<dl>
<dd>
<img src='images/<%#Eval("picture") %>' />
</dd>
<dt class="dtPrice"><%#Eval("OfficialPrice") %></dt>
<dt class="dtClick"><%#Eval("Click") %></dt>
<dt class="dtName"><%#Eval("CarName") %></dt>
</dl>
</div>
</ItemTemplate>
<%--<FooterTemplate>展示完毕——尾部</FooterTemplate>--%>
</asp:Repeater>
</div>
</form>
</body>
</html>
示例练习3:在页面增加搜索功能
要求:在当前页面中,增加一个搜索功能,允许通过汽车名称搜索
第一步,设计搜索框:在CarListRepeater.aspx文件,设计搜索框,调用控件
<div id="search">
请输入:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="搜索" />
</div>
第二步,给按钮添加事件:双击【搜索】按钮,进入事件编写
protected void Button1_Click(object sender, EventArgs e)
{
//获取用户输入的内容
string name = this.TextBox1.Text;
//声明查询语句,这里使用like进行模糊查询
string sql = "select * from Scar where CarName like '%"+name+"%'";
this.Repeater1.DataSource = DBHelper.getDataSet(sql).Tables[0];
this.Repeater1.DataBind();
}
第三步,允许测试:
案例思考:如果用户在搜索框里,什么都没有输入,搜索结果会是什么?为什么会是这样的结果?
2.2 在 Repeater 控件中删除数据
Repeater 控件不支持编辑、删除、排序等功能,所有的事件必须自行编写代码处理。当点 击 Repeater 中的按钮控件时会触发 Repeater 控件的 ItemCommand 事件。为了标识单击的按钮, 可以设置按钮的 CommandName 属性。在进行删除或者编辑操作时,都需要本行车型的编号,可以 设置按钮的 CommandArgument 属性来保存本行的车型编号。
示例练习4:在 Repeater 控件中删除数据
要求:在CarListRepeater.aspx页面中,增加一个删除功能,允许删除数据信息。
第一步,设计删除按钮:打开CarListRepeater.aspx文件,调用Button控件,增加一个【删除】按钮
第二步,给删除按钮添加属性:在利用Repeater控件绑定数据时,因为每一项(ItemTemplate)只用一个ItemCommand事件,但是有可能ItemTemplate中的多个元素都可能激活这个事件,为了快速识别是谁激活这个事件时,就可以利用CommandName与CommandArgument了。 用法:在激活事件的元素属性中,如LinkButton, Button等都可以指定CommandName与CommandArgument属性。
- CommandName:就是激活元素的名称,在ItemCommand的事件处理程序中确定激活元素。
- CommandArgument:是传递给ItemCommand的事件处理程序的参数。
<dt><asp:Button ID="Button2" runat="server" Text="删除" CommandArgument='<%#Eval("CarId") %>' CommandName="del"/></dt>
第三步,添加ItemCommand事件:将CarListRepeater.aspx文件切换到【拆分】模式,选中Repeater控件,在属性面板,找到ItemCommand事件,双击即可。
第四步,编写事件代码:在默认打开的ItemCommand事件中,编写代码。首先利用CommandArgument属性获取前台传递的汽车编号(主键),然后利用CommandName属性获取前台传递的按钮命令数据,然后进行判断,如果是删除,则执行删除数据操作。
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//使用对象的CommandArgument属性,获取前台传递过来的参数CarId
string carId = e.CommandArgument.ToString();
//使用对象的CommandName属性,获取前台传递过来的命令名称(前台可能有多个按钮,需要区分不同按钮)
string name = e.CommandName.ToString();
if(name == "del")//如果是删除命令,那么执行删除数据操作
{
string sql = "delete from Scar where CarId=" + carId;
int i = DBHelper.GetExecute(sql);
if( i > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "DelSuccess", "<script>alert('删除成功')</script>");
//删除成功后,要重新绑定一下数据源
BindRepeater();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "DelFail", "<script>alert('删除失败')</script>");
}
}
}
第五步,运行测试:
第六步,增加一个删除确认:为了更好的优化页面,当用户点击【删除】按钮时,先给用户一个“是否删除”的提示。实现方法:给【删除】按钮添加一个OnClientClick属性。OnClientClick 属性用于设置当 Button 控件被点击时运行一段客户端脚本。
<dt><asp:Button ID="Button2" runat="server" Text="删除" CommandArgument='<%#Eval("CarId") %>' CommandName="del" OnClientClick="return confirm('确认是否删除')"/></dt>
运行测试:
2.3 在 Repeater 控件中编辑数据
示例练习5:在 Repeater 控件中编辑数据
要求:车型数据展示提供【编辑】选项,用户点击以后,可以进入编辑页面进行编辑。
第一步,添加Web窗体:在示例4 的基础上,右键单击项目名称【WebApplication7】, 依次点击【添加】→【添加Web窗体】,在弹出的【指定项名称】窗口中,命名editCar,然后单击【确定】
第二步,增加编辑链接:打开CarListRepeater.aspx文件,使用a标签,增加一个【编辑】链接
<dt><a href='editCar.aspx?carId=<%#Eval("CarId") %>'>编辑</a></dt>
第三步,设计编辑页面:打开editCar.aspx文件,使用控件,设计页面
第四步,编写后置代码:在editCar.aspx文件页面,单击鼠标右键后,点击【查看代码】,编写代码。
第五步,给按钮添加事件:打开editCar.aspx文件,切换到【拆分】模式,双击按钮【修改】,进入该按钮的点击事件,编写代码
完整代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class editCar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)//将原有数据信息,填充到对应控件里
{
//获取上一个页面传递过来的carId
string carId = Request.QueryString["carId"];
this.Label1.Text = carId;
//通过主键列,查找数据源
string sql = "select * from Scar where CarId=" + carId;
DataTable dt = DBHelper.getDataSet(sql).Tables[0];
this.TextBox1.Text = dt.Rows[0]["CarName"].ToString();
this.TextBox2.Text = dt.Rows[0]["OfficialPrice"].ToString();
this.Image1.ImageUrl ="~/images/"+ dt.Rows[0]["Picture"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//获取用户修改的信息
string carName = this.TextBox1.Text;
string price = this.TextBox2.Text;
//获取上一个页面传递过来的carId
string carId = Request.QueryString["carId"];
string sql = "update Scar set CarName='" + carName + "',OfficialPrice='" + price + "' where CarId=" + carId;
int i = DBHelper.GetExecute(sql);
if (i > 0)
{
Response.Redirect("CarListRepeater.aspx");
}
else
{
Response.Write("修改失败");
}
}
}
}
第六步,运行测试:
本课总结:
- DataList 控件可用于创建模板化的列表数据,可用于设计任何重复结构中的数据。
- DataList 常用的模板类型包括:ItemTemplate 用于显示项,AlternatingItemTemplate 用 于显示交替项,EditItemTemplate 用于显示编辑项, SeparatorTemplate 用于在两个项之 间显示。
- 实现 DataList 控件的分页需要借助于 PagedDataSource 控件或者执行存储过程。
- Repeater 控件不会自动生成任何 HTML 标签,所以带来了效率上的提升,也使精确展示内容 成为可能。
- 实现 Repeater 的分页方法和 DataList 一样,可以使用 PagedDataSource 也可以调用存储过 程实现,只不过呈现数据的载体不一样而已。
- Repeater 控件不支持编辑、删除、排序等功能,所有的事件必须自行编写代码处理。当点 击 Repeater 中的按钮控件时会触发 Repeater 控件的 ItemCommand 事件。
- 设置 CommandName 属性来标识 Repeater 控件中的按钮。
- 设置按钮的 CommandArgument 属性来标识需要被操作的数据,可能是主键。
============这里是结束分割线================