如何解析ListView Item Template中的数据绑定项并计算Price字段总和
问题原因
- 你在所有行的内联代码中硬编码了
index = 0,每次执行都会固定读取ListView第0条记录的Price字段值计算总和,因此所有行展示的计算结果都和第0行一致。
推荐解决方案
方案1:直接使用绑定表达式(最简单,无需额外控件和后台代码)
直接在ItemTemplate需要展示总和的位置,插入以下绑定代码即可,不需要额外加隐藏的Label控件:
<%# Eval("Price") == DBNull.Value ? 0 : Eval("Price").ToString().Split(';').Select(int.Parse).Sum() %>
如果需要兼容Price为空字符串的场景,可以调整为:
<%# string priceStr = Eval("Price")?.ToString() ?? ""; priceStr == "" ? 0 : priceStr.Split(';').Select(int.Parse).Sum() %>
方案2:使用ItemDataBound事件(适合有更复杂计算逻辑的场景)
- 首先给ListView添加
OnItemDataBound事件绑定:
<asp:ListView ID="YourListViewID" runat="server" OnItemDataBound="YourListViewID_ItemDataBound">
- 在ItemTemplate中添加用来展示总和的Label:
<asp:Label ID="SumTotalLabel" runat="server"></asp:Label>
- 后台添加对应的事件处理方法:
protected void YourListViewID_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { // 找到当前行的隐藏Price标签 Label priceLabel = e.Item.FindControl("ItemPrice") as Label; if (priceLabel != null && !string.IsNullOrEmpty(priceLabel.Text)) { int sum = priceLabel.Text.Split(';').Select(int.Parse).Sum(); // 给当前行的总和展示标签赋值 Label sumLabel = e.Item.FindControl("SumTotalLabel") as Label; if (sumLabel != null) { sumLabel.Text = sum.ToString(); } } } }
内容的提问来源于stack exchange,提问作者J-No
相关产品推荐
相关产品推荐

