VB.NET运行抛出System.ArgumentException异常,相关业务代码如下
VB.NET 绘制DataGridView内容时System.ArgumentException错误解决方案
触发错误的核心原因
从给出的代码来看,抛出该异常的高频原因如下:
- 数组索引越界:
arrColumnLefts或arrColumnWidths数组的长度小于当前行的单元格数量,循环中用iCount访问数组时超出索引范围 - GDI绘图参数非法:矩形的宽度/高度为负数、
Cel.InheritedStyle.Font为空、strFormat字符串格式对象已被提前释放 - 资源使用不规范:循环中重复创建
SolidBrush对象未释放,累计资源泄漏后也可能触发绘图参数异常
修复方案
调整后的代码增加了参数合法性校验,同时优化了资源使用逻辑:
' 循环前初始化计数器,校验数组长度与单元格数量匹配 iCount = 0 If arrColumnLefts.Length < GridRow.Cells.Count OrElse arrColumnWidths.Length < GridRow.Cells.Count Then ' 此处可根据业务需求补充自定义错误处理逻辑 Throw New InvalidOperationException("列偏移/列宽数组长度与单元格数量不匹配") End If For Each Cel As DataGridViewCell In GridRow.Cells Dim currentColLeft As Integer = CInt(arrColumnLefts(iCount)) Dim currentColWidth As Integer = CInt(arrColumnWidths(iCount)) ' 仅在绘图参数合法时执行绘制 If currentColWidth > 0 AndAlso iCellHeight > 0 Then ' 绘制单元格文本 If Cel.Value IsNot Nothing AndAlso Cel.InheritedStyle.Font IsNot Nothing Then ' 使用Using块自动释放画刷资源,避免资源泄漏 Using cellBrush As New SolidBrush(Cel.InheritedStyle.ForeColor) e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, cellBrush, New RectangleF(currentColLeft, CSng(iTopMargin), currentColWidth, CSng(iCellHeight)), strFormat) End Using End If ' 绘制单元格边框 e.Graphics.DrawRectangle(Pens.Black, New Rectangle(currentColLeft, iTopMargin, currentColWidth, iCellHeight)) End If iCount += 1 Next
内容的提问来源于stack exchange,提问作者Rajan Shukla
相关产品推荐
相关产品推荐

