首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# Repeater綁定資料:根據指定欄位值重複時變色的ItemDataBound實戰

     編輯:程式設計綜合問答

在ASP.NET WebForms中,Repeater控制項不像GridView有內建交替列樣式,需在ItemDataBound事件中手動判斷資料值並動態套用CSS類別。本文提供完整後端代碼範例:依CurrentEarn欄位正負決定列顏色(紅/綠)。

前端頁面

<asp:Repeater ID="rpInCome" runat="server" OnItemDataBound="rpInCome_ItemDataBound">
    <ItemTemplate>
        <tr id="row" runat="server">
            <td><%# Eval("CourseName") %></td>
            <td><%# Eval("CurrentEarn") %></td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

後端代碼

protected void rpInCome_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // 僅處理資料列(Item/AlternatingItem)
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Repeater rp = (Repeater)sender;
        
        // 取得分頁資料源
        PagedDataSource pds = (PagedDataSource)rp.DataSource;
        if (pds == null || pds.Count == 0) return;

        // 定位到當前列對應的DataRowView
        IEnumerator enumerator = pds.DataSource.GetEnumerator();
        int currentIndex = 0;
        while (enumerator.MoveNext() && currentIndex != e.Item.ItemIndex)
        {
            currentIndex++;
        }
        
        DataRowView drv = (DataRowView)enumerator.Current;
        double earn = drv["CurrentEarn"] == DBNull.Value ? 0 : Convert.ToDouble(drv["CurrentEarn"]);

        // 找到行容器並套用CSS
        HtmlControl row = (HtmlControl)e.Item.FindControl("row");
        if (row != null)
        {
            row.Attributes["class"] = earn < 0 ? "green" : "red";
        }
    }
}

CSS樣式

<style>
.green { background-color: #d4edda; color: #155724; }
.red   { background-color: #f8d7da; color: #721c24; }
</style>

關鍵點解析

  1. 資料源可能是PagedDataSource:需轉型後取DataSource屬性(實際為DataView/DataTable),再用GetEnumerator()定位當前列。
  2. 用FindControl("row")取得runat="server"的容器:直接操作HtmlControl.Attributes["class"]最輕量。
  3. 處理DBNull.Value:資料庫NULL轉double會拋例外,務必三元判斷。
  4. AlternatingItem同樣處理:否則隔列不變色。

進階:依「欄位值重複」分組變色

若需「相同CategoryId的連續列同色,換組換色」:

string lastCategory = null;
bool toggle = false;

protected void rp_ItemDataBound(...) {
    // ... 取得 drv["CategoryId"] ...
    string curr = drv["CategoryId"].ToString();
    if (curr != lastCategory) {
        toggle = !toggle;
        lastCategory = curr;
    }
    row.Attributes["class"] = toggle ? "group-a" : "group-b";
}

此模式適用於報表分組、訂單狀態分色等常見業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved