【问题标题】:How to Get Count of Items in Repeater inside ItemDataBound如何在 ItemDataBound 内的 Repeater 中获取项目数
【发布时间】:2014-04-29 19:06:11
【问题描述】:

我有一个Repeater

<asp:Repeater runat="server" ID="rptID" OnItemDataBound="repID_ItemDataBound">
         <ItemTemplate>
         <a href='example.com/somepage.aspx' id="myLink">
                 <%# Eval("MyVal")%> 
         </a>
        </ItemTemplate>
</asp:Repeater>

在代码后面我需要为这个&lt;a&gt;标签添加一个css类,当转发器是一个时 项目

protected void repID_ItemDataBound(object sender, RepeaterItemEventArgs e)
  {
      if (e.Item.ItemType == ListItemType.Item || 
          e.Item.ItemType == ListItemType.AlternatingItem)
      {
          //how to set this class only then count of items is equal with 1
          ((HtmlGenericControl)e.Item.FindControl("myLink")).Attributes
                                                     .Add("class", "Count1");
      }
  }

【问题讨论】:

  • 如果当前项是第一项或者数据源只有一项,需要设置吗?
  • 如何将数据绑定到中继器?
  • @TroyCarlson 仅当 datasource.count 为 1 时
  • @Icarus rptID.DataSource = myDataTable; rptID.DataBind();

标签: c# asp.net repeater


【解决方案1】:

这将为您提供数据源项的计数:

if (((IEnumerable)rptID.DataSource).Cast<object>().Count() == 1)
{
    ((HtmlGenericControl)e.Item.FindControl("myLink")).Attributes
                                                 .Add("class", "Count1");
}

计数IEnumerable是从这个线程借来的:Calculating Count for IEnumerable (Non Generic)

【讨论】:

  • 感谢您的回答,但 rpt.DataSource.Count 不存在,“无法解析符号计数”clip2net.com/s/i3t4Wl
  • 也许我需要使用 if(rpt.Items.Count==1) ?
  • 我试过了,但它给了我同样的错误“无法解析符号'ToList'”,建议我只有这个选项i.imgur.com/UPFVKdW.png
  • var rpt = Page.FindControl("rptID") as Repeater;// 总是给我 null :(
  • 是的,它是可用的,但它在每个 itemDataBound 中递增,我必须在最后一次迭代时检查它以了解项目的实际数量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 2010-09-25
  • 1970-01-01
  • 2013-10-30
相关资源
最近更新 更多