Repeater使用详细指南
ASP.NET WebForm开发中尽量少用系统提供的runat="server"的服务器控件,尤其像GridView之类的“重量级”武器,自动生成的ViewState实在让人不敢恭维。但是用Repeater做数据绑定、展示以及表格记录处理还是很方便的。
如页面要实现下图效果:
绑定数据
数据可以用 <%#Eval("字段名")%> 这种形式在
<asp:Repeater ID="rpt" runat="server" onitemdatabound="rep_ItemDataBound">
<ItemTemplate>
<%#Eval("ID") %>、<%#Eval("Name") %>、<asp:Label ID="lblSex" runat="server" Text=""></asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
也可以用另一种方式,在CodeBehind方法rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)中进行数据绑定。
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Label lblTopicID = (Label)e.Item.FindControl("lblTopicID");
lblTopicID.Text = ((TopicType)e.Item.DataItem).TopicID.ToString();
TextBox txtTopicText = (TextBox)e.Item.FindControl("txtTopicText");
txtTopicText.Text = ((TopicType)e.Item.DataItem).Name;
Label lblCreateTime = (Label)e.Item.FindControl("lblCreateTime");
lblCreateTime.Text = ((TopicType)e.Item.DataItem).CreateTime.ToString();
Label lblLastUpdateTime = (Label)e.Item.FindControl("lblLastUpdateTime");
lblLastUpdateTime.Text = ((TopicType)e.Item.DataItem).LastTime.ToString();
}
操作每条记录
如果想对每条记录做操作(修改、删除、置顶等),可以在后台方法rpt_ItemCommand(object source, RepeaterCommandEventArgs e)中进行。
protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem ri = rpt.Items[e.Item.ItemIndex]; //选中行
Label lblTopicID = (Label)ri.FindControl("lblTopicID");
TextBox txtTopicText = (TextBox)ri.FindControl("txtTopicText");
LinkButton lbUpdateTopic = (LinkButton)ri.FindControl("lbUpdateTopic");
int topicID = CommonFunc.ToInt(lblTopicID.Text.Trim());
string topicName = txtTopicText.Text.Trim();
switch (e.CommandName)
{
case "top"://置顶
break;
case "update"://修改
break;
case "del"://删除
break;
}
}
或者使用另一种方法,在每条记录的操作按钮事件上处理,例如:
protected void lbDeleteUser_Click(object sender, EventArgs e)
{
LinkButton lbUpdateUser = (LinkButton)sender;
RepeaterItem ri = (RepeaterItem)lbUpdateUser.NamingContainer; //获取当前操作的记录所在行
TextBox txtUID = (TextBox)ri.FindControl("txtUID"); //获取当前行的ID
Label lblCn1Account = (Label)ri.FindControl("lblCn1Account");
Label lbhiddenID = (Label)ri.FindControl("lbhiddenID");
// Do Something
}