日期:2014-05-17 浏览次数:20449 次
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> <!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:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <div> <%# Eval("ID") %>,<%# Eval("Name") %>, <asp:Button ID="btnAdd" runat="server" Text="Add" CommandName="add" CommandArgument='<%# Eval("ID") %>' /> <asp:PlaceHolder ID="PlaceHolder1" runat="server" ViewStateMode="Enabled"></asp:PlaceHolder> </div> </ItemTemplate> </asp:Repeater> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Repeater1.ItemCommand += new RepeaterCommandEventHandler(Repeater1_ItemCommand); if (!IsPostBack) { List<Entity> list = new List<Entity>() { new Entity() { ID = 1, Name = "aaa"}, new Entity() { ID = 1, Name = "bbb" }, new Entity() { ID = 1, Name = "bbb" } }; Repeater1.ItemDataBound += new RepeaterItemEventHandler(Repeater1_ItemDataBound); Repeater1.DataSource = list; Repeater1.DataBind(); } } protected override void OnInit(EventArgs e) { base.OnInit(e); } protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Entity entity = (Entity)e.Item.DataItem; PlaceHolder PlaceHolder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1"); Button btnCancel = new Button(); btnCancel.ID = "btnCancel" + entity.ID; btnCancel.CommandName = "cancel"; btnCancel.CommandArgument = entity.ID.ToString(); btnCancel.Text = "Cancel " + entity.Name; PlaceHolder1.Controls.Add(btnCancel); } } public class Entity { public int ID { get; set; } public string Name { get; set; } } protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e) { Response.Write(e.CommandName); } } }