无法将样式添加到中继器的最后一项
本文关键字:最后 一项 中继器 样式 添加 | 更新日期: 2023-09-27 18:20:59
我在中继器内使用Bootstrap的进度条来显示不同项目的分数。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个项目,而不是最后一个项目。输出是这样的。有人能帮我一下吗。
为什么要在每个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));
}
}