Skip to main content
 首页 » 编程设计

c#之项目正在循环 Repeater 的 ItemDataBound 事件中的所有项目

2024年02月05日15powertoolsteam

我的 aspx 页面中有一个普通的 Repeater 控件

 <asp:Repeater ID="rpt1" runat="server" OnItemDataBound="rpt1_ItemDataBound"> 
<ItemTemplate> 
<asp:CheckBox ID="chks" runat="server" /> 
<asp:TextBox ID="txtName" runat="server" CssClass="form-control" Text='<%# DataBinder.Eval(Container,"DataItem.Name").ToString()%>'></asp:TextBox><asp:Label ID="lblValue" runat="server" Visible="false" Text='<%# DataBinder.Eval(Container,"DataItem.Id").ToString() %>'></asp:Label> 
</ItemTemplate> 
</asp:Repeater> 

在按钮上单击我将数据绑定(bind)到 Repeater as

rpt1.DataSource = GetData(); 
rpt1.DataBind(); 

绑定(bind)后 ItemDataBound 事件被调用。因为我正在循环遍历转发器项目以进行一些操作

protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
 
    foreach (RepeaterItem item in rpt1.Items) 
    { 
        if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) 
        { 
             string val = ((Label)item.FindControl("lblValue")).Text; 
            // Some Stuff 
        } 
    } 
} 

问题是循环每次都从第一个开始。

对于 Ex,如果我的数据是 1 2 3 等等......

迭代为

1 
1 2 
1 2 3 

我怎样才能把它变成

1 
2 
3 

我做错了什么

请您参考如下方法:

ItemDataBound已经为转发器中的每个项目调用,因此您不需要那里的循环。

protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    { 
         string val = ((Label)e.Item.FindControl("lblValue")).Text; 
        // Some Stuff 
    } 
} 

旁注:适用于所有 Data-Bound Web Server Controls .