You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET绑定Access数据到图表时Fill报Connection未初始化如何解决

错误根因

触发该异常的直接原因是你的数据库命令对象未关联有效连接,也没有指定查询语句:

  • 新创建的OleDbCommand没有绑定已经初始化的DBCon连接对象
  • 没有给OleDbCommand配置查询SQL,数据适配器不知道要拉取什么数据

另外你的图表绑定逻辑也存在多处顺序错误、属性赋值错误,即使解决了数据库拉取问题也无法正常渲染图表,修复后的完整代码如下:

Imports System.Data.OleDb
Imports System.Windows.Forms.DataVisualization.Charting

Public Class frmSalesAndRevenue
    Dim DBDA As New OleDbDataAdapter
    Dim DS As New DataSet
    Private DBCmd As New OleDbCommand
    ' 连接字符串请根据实际情况调整
    Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
                                         "Data Source=|DataDirectory|\NewHotel.mdb;")

    Private Function NotEmpty(text As String) As Boolean
        Return Not String.IsNullOrEmpty(text)
    End Function

    Private Sub frmSalesAndRevenue_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' 给命令对象绑定连接
        DBCmd.Connection = DBCon
        ' 替换成你实际的查询SQL,要保证查询结果包含DateBooked和Revenue两个字段
        DBCmd.CommandText = "SELECT DateBooked, Revenue FROM 你实际的业务表名"
        DBDA = New OleDbDataAdapter(DBCmd)
        ' Fill方法会自动打开/关闭连接,不需要手动Open/Close
        DBDA.Fill(DS, "chtRevenue")
    End Sub

    Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
        ' 先清空旧配置
        chtRevenue.ChartAreas.Clear()
        chtRevenue.Series.Clear()
        chtRevenue.ChartAreas.Add("ChartArea1")

        ' 配置坐标轴
        With chtRevenue.ChartAreas("ChartArea1")
            .AxisX.Title = "预订日期"
            .AxisX.MajorGrid.LineColor = Color.Purple
            .AxisY.Title = "营收"
            .AxisY.MajorGrid.LineColor = Color.Purple
        End With

        ' 配置系列
        chtRevenue.Series.Add("revenue received")
        With chtRevenue.Series("revenue received")
            .Color = Color.Purple
            .ChartType = SeriesChartType.Column
            ' 绑定X、Y轴对应的字段
            .XValueMember = "DateBooked"
            .YValueMembers = "Revenue"
        End With

        ' 绑定数据源并刷新
        chtRevenue.DataSource = DS.Tables("chtRevenue")
        chtRevenue.DataBind()
    End Sub
End Class

注意事项

  • 请将代码中的你实际的业务表名替换为你Access数据库里存储预订日期和营收数据的表名
  • 保证你的表中存在DateBooked(日期类型)和Revenue(数值类型)两个字段,字段名如果不一致请同步修改SQL和绑定的字段名

内容的提问来源于stack exchange,提问作者xxtuemonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:27:02