GridView预算数据合计行实现时遇InvalidCastException错误求助
GridView预算数据合计行实现时遇InvalidCastException错误求助
嘿,我完全懂你现在的烦恼——给显示预算数据的GridView加合计行时触发了InvalidCastException,肯定折腾得头大吧😅。先帮你拆解问题根源,再一步步给出解决办法。
首先,你数据库里的amtAllocated、amtSpent、amtRemaining是numeric(7,2)类型,对应.NET里的decimal类型,这类报错大多是类型转换不匹配或者空值处理不当导致的,咱们从核心逻辑开始梳理:
第一步:先给GridView绑定行绑定事件
你的DeptBudgetView已经开了ShowFooter="true",首先要给它加上行绑定事件属性:
<asp:GridView ID="DeptBudgetView" runat="server" ... ShowFooter="true" OnRowDataBound="DeptBudgetView_RowDataBound">
第二步:后台编写合计计算逻辑
在后台代码里声明全局变量存储合计值,然后在RowDataBound事件里处理数据行累加和页脚显示:
// 全局变量存当前页(或全量)合计值 private decimal totalAllocated = 0; private decimal totalSpent = 0; private decimal totalRemaining = 0; protected void DeptBudgetView_RowDataBound(object sender, GridViewRowEventArgs e) { // 处理数据行,累加数值 if (e.Row.RowType == DataControlRowType.DataRow) { // 重点:先判断是否为空,再安全转换为decimal decimal allocated = DataBinder.Eval(e.Row.DataItem, "amtAllocated") != DBNull.Value ? Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "amtAllocated")) : 0; decimal spent = DataBinder.Eval(e.Row.DataItem, "amtSpent") != DBNull.Value ? Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "amtSpent")) : 0; decimal remaining = DataBinder.Eval(e.Row.DataItem, "amtRemaining") != DBNull.Value ? Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "amtRemaining")) : 0; // 累加合计 totalAllocated += allocated; totalSpent += spent; totalRemaining += remaining; } // 处理页脚行,显示最终合计 else if (e.Row.RowType == DataControlRowType.Footer) { // 注意列索引:你的列顺序是【部门名称、分配额、已花费、剩余额、生效日期】,所以索引是1、2、3 e.Row.Cells[1].Text = $"合计: {totalAllocated.ToString("C2")}"; e.Row.Cells[2].Text = $"合计: {totalSpent.ToString("C2")}"; e.Row.Cells[3].Text = $"合计: {totalRemaining.ToString("C2")}"; // 给合计行加样式,和表头呼应更美观 e.Row.Font.Bold = true; e.Row.ForeColor = System.Drawing.Color.White; e.Row.BackColor = System.Drawing.Color.FromArgb(146, 30, 51); } }
第三步:排查InvalidCastException的常见坑
如果还是报错,大概率是这几个问题:
- 空值未处理:数据库里的字段可能为
NULL,直接转decimal会报错,一定要先判断DBNull.Value - 数据源类型不对:如果你的数据源(比如DataTable)里这些字段是
string/int类型,转换时必然报错,要确保数据源字段是decimal - 列索引搞混:别把合计要显示的列索引写错,比如把剩余额写到生效日期的列里
- 分页场景的合计范围:上面的代码默认只算当前页的合计,如果要算全量数据的合计,得提前从数据库查总合计(比如
SELECT SUM(amtAllocated) FROM 你的表名),再直接赋值给页脚
另外你贴的VendorBudgetView代码没写完,不过逻辑完全一致,只要开启ShowFooter="true",复制上面的事件逻辑改改字段名就行。
内容来源于stack exchange
相关产品推荐
相关产品推荐

