无法将样式添加到Repeater的最后一项

时间:2014-09-08 14:01:15

标签: c# asp.net .net twitter-bootstrap webforms

我在转发器中使用Bootstrap's Progress Bar来显示不同项目的得分。 aspx是这样的:

    <asp:Repeater ID="rptFinalScore" runat="server" OnItemDataBound="rptFinalScore_ItemDataBound">
<ItemTemplate>
    <div class="row">
         <div class="col-sm-2">
            <asp:Label ID="rpt_Score" runat="server" Text='<%#Eval("TotalScore") %>'>></asp:Label>
        </div>                    
        <div class="col-sm-10">
            <div class="progress">
                <div id="rpt_proBar" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" runat="server">                                                                
                </div>
            </div>
        </div>
    </div>
</ItemTemplate>
</asp:Repeater>  

,代码隐藏是:

protected void rptFinalScore_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    foreach (RepeaterItem item in rptFinalScore.Items)
    {                
        if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
        {
            var Score = item.FindControl("rpt_Score") as Label;
            var ProgBar = item.FindControl("rpt_proBar") as HtmlGenericControl;
            string BuildingScore = ((Label)Score).Text;
            ProgBar.Attributes.Add("style", string.Format("width:{0}%;", BuildingScore));           
        }
    }
}

我面临的问题是,如果假设转发器中有5个项目,那么它将正确地将style="width:x%"应用于前4个项目,但不适用于最后一个项目。输出类似于this。有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

为什么要在每个ItemDataBound事件处理程序调用中循环?您必须为存储在e参数中的相应项设置样式。未设置最后一项的样式,因为在触发ItemDataBound事件时,转发器的Items集合中没有该项。 您必须将ItemDataBound处理程序更改为以下内容:

protected void rptFinalScore_ItemDataBound(object sender, RepeaterItemEventArgs e)
{             
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var Score = e.Item.FindControl("rpt_Score") as Label;
            var ProgBar = e.Item.FindControl("rpt_proBar") as HtmlGenericControl;
            string BuildingScore = ((Label)Score).Text;
            ProgBar.Attributes.Add("style", string.Format("width:{0}%;", BuildingScore));           
        }
}