我正在使用带有DataGridView的VB.NET 2008,并且我使用vfpoledb.1驱动程序连接到Visual Foxpro 6数据库。当我更改说明字段中的值时,它会在DataGridView中更改,但数据库永远不会更新。我是否需要使用代码来强制进行更改?
这是我正在使用的代码:
Imports System.Data.OleDb
Public Class Form1
Dim sConString As String = "Provider=vfpoledb.1;Data Source=C:\MyDatabase.dbc;Mode=3;"
Dim con As OleDbConnection = New OleDbConnection(sConString)
Private Function FetchData()
con.Open()
Dim ds As DataSet = New DataSet()
Dim sSQL As String
sSQL = "SELECT item_cd, item_desc FROM invent;"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, con)
Dim daInv As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim iRecCount As Integer
iRecCount = daInv.Fill(ds, "invent")
Me.DataGridView1.DataSource = ds.Tables("invent").DefaultView
End Function
Private Sub btnFetchData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFetchData.Click
Call FetchData()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
con.Close()
con = Nothing
End Sub
End Class
答案 0 :(得分:0)
此代码是否会更新表并将更改推送回数据库?我不这么认为。我尝试使用SQL Server 2005相同的代码,它不工作(我没有FoxPro数据库)。所以我修改了代码,现在它工作正常。
Imports System.Data.OleDb
Public Class Form1
Dim sConString As String = "Provider=vfpoledb.1;Data Source=C:\MyDatabase.dbc;Mode=3;"
Dim con As OleDbConnection = New OleDbConnection(sConString)
Dim daInv As OleDbDataAdapter
Dim ds As DataSet = New DataSet()
Private Sub FetchData()
con.Open()
Dim sSQL As String
sSQL = "SELECT item_cd, item_desc FROM invent;"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, con)
daInv = New OleDbDataAdapter(cmd)
Dim builder As New OleDbCommandBuilder(daInv)
Dim iRecCount As Integer
iRecCount = daInv.Fill(ds, "invent")
Me.DataGridView1.DataSource = ds.Tables("invent").DefaultView
End Sub
Private Sub btnFetchData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFetchData.Click
Call FetchData()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs)
daInv.Update(ds.Tables("invent"))
con.Close()
con = Nothing
End Sub
End Class
希望它有效:)
答案 1 :(得分:0)
我找到了底层问题并解决了它。我正在访问的VFP表没有定义主键。它确实有索引,但它们只是标记为“常规”索引(使用VFP术语)。
我能够使用Ed Leafe网站上的VFP工具调用vRunFox(Visual Run Fox)来修改表结构。我不得不使用一些VFP命令调出Table Designer窗口。
我还必须在FormClosing事件中添加一些代码。这是我的FormClosing事件现在的样子:
Dim myBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daInv)
myBuilder.GetUpdateCommand()
daInv.UpdateCommand = myBuilder.GetUpdateCommand
daInv.Update(ds.Tables("invent"))
con.Close()
con = Nothing