You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析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事件(适合有更复杂计算逻辑的场景)

  1. 首先给ListView添加OnItemDataBound事件绑定:
<asp:ListView ID="YourListViewID" runat="server" OnItemDataBound="YourListViewID_ItemDataBound">
  1. 在ItemTemplate中添加用来展示总和的Label:
<asp:Label ID="SumTotalLabel" runat="server"></asp:Label>
  1. 后台添加对应的事件处理方法:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:48:00