GridView中TextBox文本变更事件统计页脚合计时最后一行未计算问题求助
问题根因
你的代码存在两个核心问题导致最后一行未计入合计:
- 空
catch块吞掉了所有运行时异常:如果最后一行的数量输入值为空、格式非法,转换数值时会抛出异常,直接中断合计循环,后续(包括最后一行)的计算就会终止,且你看不到任何报错提示。 - 修改页脚文本后未触发GridView重绑定,页脚展示的内容不会更新为最新计算值。
修正后的后台代码
protected void TxtQuantity_TextChanged(object sender, EventArgs e) { try { decimal temptotal = 0; foreach (GridViewRow currentRow in GrdBindDenomination.Rows) { // 仅处理数据行,跳过页眉/页脚行 if (currentRow.RowType != DataControlRowType.DataRow) continue; TextBox quantityA = (TextBox)currentRow.FindControl("TxtQuantity"); Label Value = (Label)currentRow.FindControl("Value"); Label Total = (Label)currentRow.FindControl("Total"); // 安全转换,避免格式错误抛异常中断计算 if (decimal.TryParse(quantityA.Text, out decimal quantity) && decimal.TryParse(Value.Text, out decimal denominationValue)) { decimal grandTotal1 = denominationValue * quantity; Total.Text = Convert.ToInt32(grandTotal1).ToString(); temptotal += grandTotal1; } else { // 输入格式错误时当前行合计置0 Total.Text = "0"; } } GrdBindDenomination.Columns[3].FooterText = temptotal.ToString(); GrdBindDenomination.Columns[3].FooterStyle.HorizontalAlign = HorizontalAlign.Left; GrdBindDenomination.Columns[2].FooterText = "Total"; // 新增:触发GridView重绑定,让页脚修改生效 GrdBindDenomination.DataBind(); } catch (Exception ex) { // 此处可根据需求添加异常日志逻辑,不要直接吞掉错误 throw; } }
额外优化说明
- 新增了行类型判断,只处理数据行,避免误操作页眉页脚行的控件
- 用
TryParse做数值转换,即使某行输入格式错误也不会中断整个合计计算
内容的提问来源于stack exchange,提问作者Genish Parvadia
相关产品推荐
相关产品推荐

