2011-12-09 57 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....