VB.NET中实现Chart控件绑定DataGridView数据生成柱状图及空值异常解决求助
解决Chart柱状图生成时的System.ArgumentNullException错误
看起来你遇到的问题是在往Chart控件添加数据点时,传入了空的x轴值。咱们先分析原因,再给出修复方案:
问题原因
报错System.ArgumentNullException: 'Value cannot be null. Parameter name: xValue'明确说明,你的AddXY方法中的第一个参数(x轴值)是Nothing。可能的触发场景有三种:
- DataGridView自动添加的空新行(默认开启
AllowUserToAddRows时,最后一行是空的,所有单元格值都是Nothing) - XML文件中存在某条记录的第一列数据缺失,导致DataGridView对应单元格为空
- 直接访问
Item(0, Count).Value时,单元格未绑定到有效数据
修复方案
我给你两种可行的修复方式,你可以根据自己的场景选择:
方案1:修正DataGridView循环逻辑,跳过空行和空值
这个方案在你原代码的基础上修改,增加空值检查和空行过滤:
'collects data from the XMl file "Financial_Planner" then displays it onto a DataGrid Dim MyXMlFile = "Financial_Planner.xml" If My.Computer.FileSystem.FileExists(MyXMlFile) = True Then DsFinancialPlanner.ReadXml(MyXMlFile) End If 'Creates a Column Graph graFullGraph.Series(0).ChartType = DataVisualization.Charting.SeriesChartType.Column graFullGraph.Series(0).Points.Clear() '循环遍历DataGridView行,跳过空行并检查值有效性 For Count As Integer = 0 To DtabFinancialDetailsDataGridView.Rows.Count - 1 '跳过DataGridView的空新增行 If DtabFinancialDetailsDataGridView.Rows(Count).IsNewRow Then Continue For End If '获取x、y轴值并检查是否为空 Dim xVal = DtabFinancialDetailsDataGridView.Item(0, Count).Value Dim yVal = DtabFinancialDetailsDataGridView.Item(1, Count).Value '仅当两个值都不为空时才添加数据点 If xVal IsNot Nothing AndAlso yVal IsNot Nothing Then graFullGraph.Series(0).Points.AddXY(xVal, yVal) End If Next
方案2:直接从DataSet的DataTable读取数据(更推荐)
既然数据已经读到DsFinancialPlanner这个DataSet里了,直接操作底层的DataTable比通过DataGridView的UI层读取更可靠,能避免UI层的空行或显示异常:
'collects data from the XMl file "Financial_Planner" then displays it onto a DataGrid Dim MyXMlFile = "Financial_Planner.xml" If My.Computer.FileSystem.FileExists(MyXMlFile) = True Then DsFinancialPlanner.ReadXml(MyXMlFile) End If 'Creates a Column Graph graFullGraph.Series(0).ChartType = DataVisualization.Charting.SeriesChartType.Column graFullGraph.Series(0).Points.Clear() '获取DataSet中的目标DataTable(替换成你实际的表名) Dim targetTable As DataTable = DsFinancialPlanner.Tables("DtabFinancialDetails") If targetTable IsNot Nothing AndAlso targetTable.Rows.Count > 0 Then For Each row As DataRow In targetTable.Rows '检查DataRow中的值是否为数据库空值 If row(0) IsNot DBNull.Value AndAlso row(1) IsNot DBNull.Value Then graFullGraph.Series(0).Points.AddXY(row(0), row(1)) End If Next End If
额外提示
- 如果你不确定DataTable的准确名称,可以在调试时查看
DsFinancialPlanner.Tables集合,或者通过DsFinancialPlanner.Tables(0)直接取第一个表(如果DataSet只有一个表的话) - 检查你的XML文件,确保每条记录的对应列都有有效值,避免出现缺失数据的情况
内容的提问来源于stack exchange,提问作者BobDream
相关产品推荐
相关产品推荐

