2011-12-09 19 views
1

我有一个数据源Page_Load绑定到repeater获取行数在ItemDataBound

我正在将结果写入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都等于相同的每一行。

感谢您的任何帮助。 J.

回答

1

正在努力避免使用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 
+0

如果你想使用这种方法,而不是Curt建议的,我不会使用Session变量。会话变量用于必须跨多个请求保存的项目。由于所有这些都发生在一个请求中,因此您可以简单地使用在页面范围内定义的变量(页面类的成员变量)。 – eselk

3

但是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()显示中继势必在此之后,应然。

+0

我尝试你的建议,但不能得到它与我所工作所以最后我创建了一个行计数的会话,并可以从ItemDataBound访问它。 – JBoom

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....