Repeater数据绑定和操作

Repeater使用详细指南

ASP.NET WebForm开发中尽量少用系统提供的runat="server"的服务器控件,尤其像GridView之类的“重量级”武器,自动生成的ViewState实在让人不敢恭维。但是用Repeater做数据绑定、展示以及表格记录处理还是很方便的。

如页面要实现下图效果:

绑定数据

数据可以用 <%#Eval("字段名")%> 这种形式在标签中绑定,参考之前写的文章

1 <asp:Repeater ID="rpt" runat="server" onitemdatabound="rep_ItemDataBound">
2     <ItemTemplate>
3         <%#Eval("ID") %>、<%#Eval("Name") %>、<asp:Label ID="lblSex" runat="server" Text=""></asp:Label>
4         <br />
5     </ItemTemplate>
6 </asp:Repeater>

也可以用另一种方式,在CodeBehind方法rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)中进行数据绑定。

 1 protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
 2 {
 3     Label lblTopicID = (Label)e.Item.FindControl("lblTopicID");
 4     lblTopicID.Text = ((TopicType)e.Item.DataItem).TopicID.ToString();
 5 
 6     TextBox txtTopicText = (TextBox)e.Item.FindControl("txtTopicText");
 7     txtTopicText.Text = ((TopicType)e.Item.DataItem).Name;
 8 
 9     Label lblCreateTime = (Label)e.Item.FindControl("lblCreateTime");
10     lblCreateTime.Text = ((TopicType)e.Item.DataItem).CreateTime.ToString();
11 
12     Label lblLastUpdateTime = (Label)e.Item.FindControl("lblLastUpdateTime");
13     lblLastUpdateTime.Text = ((TopicType)e.Item.DataItem).LastTime.ToString();
14 }

操作每条记录

如果想对每条记录做操作(修改、删除、置顶等),可以在后台方法rpt_ItemCommand(object source, RepeaterCommandEventArgs e)中进行。

 1 protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
 2 {
 3     RepeaterItem ri = rpt.Items[e.Item.ItemIndex];    //选中行
 4     Label lblTopicID = (Label)ri.FindControl("lblTopicID");
 5     TextBox txtTopicText = (TextBox)ri.FindControl("txtTopicText");
 6     LinkButton lbUpdateTopic = (LinkButton)ri.FindControl("lbUpdateTopic");
 7 
 8     int topicID = CommonFunc.ToInt(lblTopicID.Text.Trim());
 9     string topicName = txtTopicText.Text.Trim();
10 
11     switch (e.CommandName)
12     {
13         case "top"://置顶
14 
15             break;
16         case "update"://修改
17             
18             break;
19         case "del"://删除
20 
21             break;
22     }
23 }

或者使用另一种方法,在每条记录的操作按钮事件上处理,例如:

 1 protected void lbDeleteUser_Click(object sender, EventArgs e)
 2 {
 3     LinkButton lbUpdateUser = (LinkButton)sender;
 4     RepeaterItem ri = (RepeaterItem)lbUpdateUser.NamingContainer; //获取当前操作的记录所在行
 5 
 6     TextBox txtUID = (TextBox)ri.FindControl("txtUID"); //获取当前行的ID
 7     Label lblCn1Account = (Label)ri.FindControl("lblCn1Account");
 8     Label lbhiddenID = (Label)ri.FindControl("lbhiddenID");
 9 
10     // Do Something
11 }

 

posted @ 2015-10-12 11:17  陌钰陌城  Views(804)  Comments(0Edit  收藏  举报