获取ItemDataBound中的行数

时间:2011-12-09 12:37:24

标签: asp.net repeater asp.net-4.0 itemdatabound

我有Page_Load绑定到repeater的数据源。

我正在将结果写入ItemDataBound中的页面,但是当它是最后一行数据时,我需要它做一些稍微不同的事情。

如何从转发器的ItemDataBound中访问Page_Load中数据源的行数?

我试过了:

Dim iCount As Integer
iCount = (reWorkTags.Items.Count - 1)
If e.Item.ItemIndex = iCount Then
    'do for the last row
Else
    'do for all other rows
End If

但是e.Item.ItemIndex和iCount对于每一行都是相同的。

感谢您的帮助。 学家

4 个答案:

答案 0 :(得分:4)

  

但是e.Item.ItemIndex和iCount对于每一行都是相同的。

这是因为项目仍然具有约束力。当绑定时,Count将是当前项索引的+1。

我认为最好在repeater完全绑定后执行此操作。

因此,您可以将以下内容添加到Page_Load

rep.DataBind()

For each item as repeateritem in rep.items
   if item.ItemIndex = (rep.Items.Count-1)
       'do for the last row
   else
       'do for all other rows
   end if
Next

注意:我刚刚添加rep.DataBind()以显示应该在转发器绑定后运行。

答案 1 :(得分:1)

是为了避免使用Sessions,但最终还是使用了Sessions。

我刚刚创建了一个行计数会话,可以从ItemDataBound中访问它。

Protected Sub reWorkTags_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles reWorkTags.ItemDataBound


    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then

        Dim rowView As System.Data.DataRowView
        rowView = CType(e.Item.DataItem, System.Data.DataRowView)

        Dim link As New HyperLink
        link.Text = rowView("tag")
        link.NavigateUrl = rowView("tagLink")
        link.ToolTip = "View more " & rowView("tag") & " work samples"

        Dim comma As New LiteralControl
        comma.Text = ", "

        Dim workTags1 As PlaceHolder = CType(e.Item.FindControl("Linkholder"), PlaceHolder)

        If e.Item.ItemIndex = Session("iCount") Then
            workTags1.Controls.Add(link)
        Else
            workTags1.Controls.Add(link)
            workTags1.Controls.Add(comma)
        End If

    End If

End Sub

答案 2 :(得分:1)

这是一个老问题,但我最近有这个确切的情况。我需要为除了最后一个项目之外的每个项目写出标记。

我在我的用户控件类中创建了一个私有成员变量,并将其设置为绑定到我的转发器的数据源的count属性,并从中减去1。由于索引是基于零的,因此索引值与计数相差一个。

private long itemCount {get;组; }

在Page_Load或您调用DataBind的任何方法中:

            //Get the count of items in the data source. Subtract 1 for 0 based index.
            itemCount = contacts.Count-1;

            this.repContacts.DataSource = contacts;
            this.repContacts.DataBind();

最后,在你的绑定方法

           //If the item index is not = to the item count of the datasource - 1

            if (e.Item.ItemIndex != itemCount)
                Do Something....

答案 3 :(得分:0)

发生数据绑定时,将为转发器设置数据源。因此,您可以在ItemDataBound事件处理程序中获取它,并根据项目索引对其进行检查。这样可以避免使用Session或局部变量。

var datasource = (ICollection)reWorkTags.DataSource;

if (e.Item.ItemIndex + 1 == datasource.Count)
{
    // Do stuff
}