System.InvalidOperationException: 'Fill: SelectCommand.Connection 属性尚未初始化。



我有一个图表在VB。DBDA.Fill(DS, "chtRevenue")

的标题中出现了错误。有什么我错过了或这个代码是不正确的?

我是一个编程新手,我从来没有使用过图表。

图表应该从访问数据库中提取日期。

这是与问题相关的所有代码:

Imports System.Data.OleDb
Imports System.Windows.Forms.DataVisualization.Charting
Public Class frmSalesAndRevenue
Private DB As New DBControl
Dim DBDA As New OleDbDataAdapter
Dim DS As New DataSet
Private DBCmd As New OleDbCommand
Private READ As OleDbDataReader
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
DBCon.Open()
DBCmd = New OleDbCommand
DBDA = New OleDbDataAdapter(DBCmd)
DBDA.Fill(DS, "chtRevenue")
DBCon.Close()
End Sub
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
'Clear old graph and plot new graph
chtRevenue.ChartAreas.Clear()
chtRevenue.ChartAreas.Add("ChartArea1")
With chtRevenue.ChartAreas("ChartArea1")
.AxisX.Title = "DateBooked"
.AxisX.MajorGrid.LineColor = Color.Purple
.AxisY.Title = "Revenue"
.AxisX.MajorGrid.LineColor = Color.Purple
End With
Dim Series As Series = chtRevenue.Series("revenue received")
chtRevenue.DataSource = DS.Tables("chtRevenue")
'Clear series and add new series
chtRevenue.Series.Clear()
chtRevenue.Series.Add("revenue received")
chtRevenue.Series("revenue received").Color = Color.Purple
chtRevenue.Series("revenue received").ChartType = DataVisualization.Charting.SeriesChartType.Column
With chtRevenue
.Series(0).XValueMember = "DateBooked"
.Series(0).XValueMember = "Revenue"
End With
Dim x As DateTime
Dim y As Int32
chtRevenue.Series("revenue received").Points.Add(x.ToOADate(), y)
End Sub

感谢您的宝贵时间:)

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

这个函数似乎没有什么用途。只需在代码中直接使用String.IsNullOrEmpty()方法即可。

不要在使用连接的方法之外声明连接。Connections和DataAdapters需要处理。Using...End Using块就是为此目的而提供的。DataAdapter的构造函数可以接受CommandText和连接。DataAdapter将打开和关闭连接,作为Fill方法的一部分。

Dim DS As New DataSet
Private MyConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|NewHotel.mdb;"
Private Sub frmSalesAndRevenue_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using DBCon As New OleDbConnection(MyConStr),
DBDA As New OleDbDataAdapter("Select SomeFields From SomeTable", DBCon)
DBDA.Fill(DS, "chtRevenue")
End Using
End Sub

最新更新