Repeater控件属于一种轻量级的数据绑定控件,它能触发的事件很少
- ItemCommand:在Repeater中生成事件时触发;
- ItemCreated:在创建项时触发
- ItemDataBound:在项被数据绑定后触发
例子:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="Repeater1_ItemCreated">
<HeaderTemplate>
<table>
<tr>
<td>ID</td>
<td>操作</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("ID") %>
</td>
<td>
<asp:LinkButton ID="LinkButton1" runat="server">入库</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(System.Int32));
for (int i = 0; i < 10; i++) {
DataRow r = dt.NewRow();
r[0] = i;
dt.Rows.Add(r);
}
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
LinkButton lb = (LinkButton)e.Item.FindControl("LinkButton1");
if (lb != null) {
lb.Click += new EventHandler(LinkButton1_Click); //关键在这里给LinkButton添加Click事件
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb=(LinkButton)sender;
RepeaterItem rt = (RepeaterItem)lb.Parent; //关键在这里找到Repeater当前绑定项
Label1.Text =((DataBoundLiteralControl)rt.Controls[0]).Text;
}
}
上面给出了一个简单的例子,其它的复杂操作可以根据这个举一反三。