我想将对DataGridView所做的更改保存到数据库MS SQL CE中, 但我不能,更改不会保存到数据库....
这个代码(VB.net):
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) handles MyBase.Load
Dim con As SqlCeConnection = New SqlCeConnection(@"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'
Me.Validate()
Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
Me.myDataSet.AcceptChanges()
'
End Sub
感谢您的任何建议。
答案 0 :(得分:0)
您需要使用myDA.Update,它将提交更改。这是因为您正在进行的任何更改都是在该数据集的本地实例中进行的。因此处理就像任何其他变量一样。
...我可以在你的edit_rec子中看到,但是调用的是什么 - 你发布的代码中没有任何内容。
答案 1 :(得分:0)
也许有点晚了。
在表单加载事件中,您可以打开和关闭连接。 此外,所有都是局部变量,在离开子
时会丢失任何值或数据Public Class Form1
Dim con As SqlCeConnection
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con = New SqlCeConnection(@"Data Source=C:\Users\utente\Documents\test.sdf")
Dim cmd As SqlCeCommand = New SqlCeCommand("SELECT * FROM mytable", con)
con.Open()
myDA = New SqlCeDataAdapter(cmd)
Dim builder As SqlCeCommandBuilder = New SqlCeCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
cmd.Dispose()
End Sub
***Put the closing of connection here instead or somewhere else suitable when you don't use it anymore***
Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
con.Close()
con = Nothing
End Sub
Private Sub edit_rec()
Dim txt1, txt2 As String
Dim indice As Integer = DataGridView1.CurrentRow.Index
txt1 = DataGridView1(0, indice).Value.ToString '(0 is the first column of datagridview)
txt2 = DataGridView1(1, indice).Value.ToString '(1 is the second) MsgBox(txt1 + " " + txt2)
'
DataGridView1(0, indice).Value = "Pippo"
DataGridView1(1, indice).Value = "Pluto"
'You code to update goes here and not in my scope of answer
End Sub
End Class
答案 2 :(得分:0)
我想你想用连接字符串
添加@SqlConnection con;
con = New SqlConnection(@"Data Source=C:\Users\utente\Documents\test.sdf");