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

GridView Footer列求和问题:无法计算第9列总计值

解决ASP.NET GridView Footer计算列总和问题

问题根源

你的ItemTotal列值是通过<asp:Label>控件渲染的,直接读取row.Cells[9].Text无法获取到Label中的计算值——单元格的Text属性不会自动包含子控件的Text;另外原代码在Page_Load调用计算方法时,GridView可能尚未完成数据绑定,导致Rows集合为空,同时未过滤非数据行(如Header、Footer)。

正确实现方案

采用方法1的安全解析思路(用int.TryParse避免格式异常),同时修正核心问题:

  1. 确保GridView开启Footer:设置ShowFooter="True"
  2. 在GridView数据绑定完成后执行计算(绑定DataBound事件)
  3. 遍历行时仅处理数据行(RowType == DataControlRowType.DataRow)
  4. 从单元格中找到Label控件再读取其Text值

完整代码示例

前端GridView配置(关键部分)

<asp:GridView ID="GridView1" runat="server" ShowFooter="True" OnDataBound="GridView1_DataBound">
    <!-- 其他列配置 -->
    <asp:TemplateField HeaderText="ItemTotal">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# ((Convert.ToInt32(Eval("Price")))*(Convert.ToInt32(Eval("Quantity"))))%>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:Label ID="lblGrandTotal" runat="server" Font-Bold="True"></asp:Label>
        </FooterTemplate>
    </asp:TemplateField>
    <!-- 其他列配置 -->
</asp:GridView>

后台代码

protected void GridView1_DataBound(object sender, EventArgs e)
{
    calculateSum();
}

private void calculateSum()
{
    int grandTotal = 0;
    foreach (GridViewRow row in GridView1.Rows)
    {
        // 仅处理数据行,跳过Header、Footer等行
        if (row.RowType == DataControlRowType.DataRow)
        {
            // 找到单元格中的Label控件
            Label lblItemTotal = (Label)row.FindControl("Label1");
            if (lblItemTotal != null)
            {
                int itemValue;
                if (int.TryParse(lblItemTotal.Text, out itemValue))
                {
                    grandTotal += itemValue;
                }
            }
        }
    }

    // 将总计值赋值给Footer
    if (GridView1.FooterRow != null)
    {
        // 方式1:直接设置单元格Text
        GridView1.FooterRow.Cells[9].Text = $"总计: {grandTotal}";
        
        // 方式2:如果Footer中用了Label,也可以找到控件赋值
        // Label lblGrandTotal = (Label)GridView1.FooterRow.FindControl("lblGrandTotal");
        // if (lblGrandTotal != null)
        // {
        //     lblGrandTotal.Text = $"总计: {grandTotal}";
        // }
    }
}

额外注意事项

  • 确认Cells[9]确实是ItemTotal列的索引(列索引从0开始,需核对列的实际顺序)
  • 如果Price或Quantity为非整数类型(如decimal),建议将计算逻辑改为decimal类型,避免精度丢失
  • 若GridView使用分页,上述代码仅计算当前页的总和;如需计算所有页的总和,需从数据源(如DataTable)中直接累加,而非遍历GridView行

内容的提问来源于stack exchange,提问作者Asad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:04:54