GridView Footer列求和问题:无法计算第9列总计值
问题根源
你的ItemTotal列值是通过<asp:Label>控件渲染的,直接读取row.Cells[9].Text无法获取到Label中的计算值——单元格的Text属性不会自动包含子控件的Text;另外原代码在Page_Load调用计算方法时,GridView可能尚未完成数据绑定,导致Rows集合为空,同时未过滤非数据行(如Header、Footer)。
正确实现方案
采用方法1的安全解析思路(用int.TryParse避免格式异常),同时修正核心问题:
- 确保GridView开启Footer:设置
ShowFooter="True" - 在GridView数据绑定完成后执行计算(绑定
DataBound事件) - 遍历行时仅处理数据行(
RowType == DataControlRowType.DataRow) - 从单元格中找到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
相关产品推荐
相关产品推荐

