首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET Repeater 控制項遍歷三大寫法對比:Controls 集合 vs Items 集合 vs 強型別 RepeaterItem

     編輯:ASP.NET 基礎

Repeater 的控制項結構特性

Repeater 無 HeaderTemplate/FooterTemplate 之外的包裝元素,其 Controls 集合直接包含 RepeaterItem 實例(類型為 RepeaterItemType.Item、AlternatingItem 等)。理解這點,三種遍歷寫法的本質差異一目瞭然。

寫法一:遍歷 Controls 集合(不推薦)

foreach (Control c in this.Repeater1.Controls) {
    var chk = c.FindControl("cbDelete1") as HtmlInputCheckBox;
    if (chk != null) chk.Checked = true;
}

缺陷:

  • Controls 可能包含非 RepeaterItem 的字面內容控制項(LiteralControl 等),需額外型別檢查。
  • 語意模糊:Repeater.Controls 非公開設計意圖,未來版本可能變更。

寫法二:索引遍歷 Items 集合(經典、相容)

for (int i = 0; i < this.Repeater1.Items.Count; i++) {
    var chk = this.Repeater1.Items[i].FindControl("cbDelete1") as HtmlInputCheckBox;
    if (chk != null) chk.Checked = true;
}

優點:

  • Items 集合僅包含 RepeaterItem,型別純淨。
  • 可隨時取得 ItemIndex(即 i),便於對應資料源索引。
  • 支援 RepeaterItemType 判斷:Items[i].ItemType == ListItemType.AlternatingItem。

寫法三:foreach 遍歷 Items 集合(現代、可讀)

foreach (RepeaterItem item in this.Repeater1.Items) {
    var chk = item.FindControl("cbDelete1") as HtmlInputCheckBox;
    if (chk != null) chk.Checked = true;
}

優點:

  • 語法簡潔,符合 C# 慣用模式。
  • 直接存取 item.ItemIndex、item.ItemType、item.DataItem。
  • 編譯器優化等同 for 迴圈,效能無差異。

進階:強型別 DataItem 存取(避免 boxing/unboxing)

// 假設資料源為 List
foreach (RepeaterItem item in Repeater1.Items) {
    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) {
        Product product = (Product)item.DataItem; // 強型別轉換
        var chk = item.FindControl("cbDelete1") as HtmlInputCheckBox;
        if (chk != null) {
            chk.Checked = product.IsDeletable;
            chk.Attributes["data-id"] = product.Id.ToString();
        }
    }
}

效能與最佳實踐總結

維度Controls 遍歷Items 索引Items foreach
型別安全低高高
可讀性低中高
索引需求需手動計算原生支援item.ItemIndex
資料項存取困難Items[i].DataItemitem.DataItem
推薦度❌✅ (需索引運算時)✅✅ (首選)

常見陷阱提醒

  1. HeaderTemplate/FooterTemplate 也在 Items 中:ItemType 為 Header/Footer,DataItem 為 null,務必判斷 ItemType 後再轉型。
  2. FindControl 返回 null:檢查 ID 拼寫、確認控制項在對應 Template 內、確認 runat="server"。
  3. 動態繫結後立即遍歷:需在 DataBind() 之後、PreRender 之前執行,否則 Items 為空。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved