Repeater控件的ItemDataBound事件-飞外

Repeater控件的ItemDataBound事件:在项被绑定数据后触发。

下面的例子来自msdn,不过我把前台和后台分开了。

前台是:

View Code
 %@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.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  h1 Repeater控件的ItemDataBound事件 /h1  form  runat="server"  div  asp:Repeater ID="repeater1" runat="server" OnItemDataBound="Repeater1_OnItemDataBound"  HeaderTemplate  table border="1"  td b Product /b /td  td b Consumer Rating /b /td  /tr  /HeaderTemplate  ItemTemplate  td asp:Label Text=' %#Eval("ProductID") % ' runat="server" /asp:Label /td  td asp:Label Text=' %#Eval("Rating") % ' ID=RatingLabel runat="server" /asp:Label /td  /tr  /ItemTemplate  FooterTemplate  /table  /FooterTemplate 

注意:table开始标签在 HeaderTemplate 中,结束标签在 FooterTemplate 中。

绑定数据Text=' %#Eval("ProductID") % '需要加单引号,里面加双引号。

后台是:

View Code
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Collections;namespace WebApplication2 public partial class WebForm1 : System.Web.UI.Page protected void Page_Load(object sender, EventArgs e) ArrayList values = new ArrayList(); values.Add(new Evaluation("Razor Wiper Blades", "Good")); values.Add(new Evaluation("Shoe-So-Soft Softening Polish", "Poor")); values.Add(new Evaluation("DynaSmile Dental Fixative", "Fair")); this.repeater1.DataSource = values;//指定数据源 this.repeater1.DataBind(); //绑定数据  protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e) // This event is raised for the header, the footer, separators, and items. // Execute the following logic for Items and Alternating Items. if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) if (((Evaluation)e.Item.DataItem).Rating == "Good") ((Label)e.Item.FindControl("RatingLabel")).Text = " b ***Good*** /b ";

该事件在Repeater控件中的某一项被数据绑定后但尚未呈现在页面上之前发生。

运行结果:

参见:http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.repeater.itemdatabound(v=vs.80).aspx

下面说一下RepeaterItemEventArgs,它为Repeater的ItemCreated和ItemDataBound事件提供数据。

如果在Repeter中有一个DropDownlist and Datalist ,然后你想根据DropDownlist的值设置Datalist的值,可以使用下面的方法来传值:


RepeaterItemEventArgs e1=new RepeaterItemEventArgs(rep); BindInnerDatalist(sender,e1, sortdir);//另外写的方法。 }