用VB语言 如何将在控件datagridview中修改数据更新到数据库? 50
2个回答
展开全部
'关键是OleDbCommandBuilder(你自己把其改成SqlClient.SqlCommandBuilder)
'以下是我现成的操作OLEDB数据库的,也就是Access2003那种,你自己修改成SQL的就可以用
'首先在窗体上加DataGridView1,BindingSource1,BindingNavigator1,Button1控件各一个,然后在BindingNavigator1控件上增加一个按钮ToolStrip_Save
修改的关键是OleDbCommandBuilder(你自己把其改成SqlClient.SqlCommandBuilder)
'--------下面是整个类代码-----------------------------------------------------------
Imports System.Data.OleDb
Public Class Form1
Dim ds As DataSet
Dim tb As DataTable
Dim ap As OleDbDataAdapter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click '手动显示
Me.DataGridView1.AllowUserToAddRows = False
tb = New DataTable
ap = New OleDbDataAdapter("select * from electic ", cn)'这里是SQL命令,Cn是数据库连接,修改成你的Conn
ap.Fill(tb)
Me.BindingSource1.DataSource = tb
Me.BindingNavigator1.BindingSource = Me.BindingSource1
Me.DataGridView1.DataSource = Me.BindingSource1
End Sub
Private Sub ToolStrip_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStrip_Save.Click '调用保存
Save_Data()
End Sub
Private Function Save_Data() As Boolean '保存数据库的操作
Try
Me.DataGridView1.EndEdit()
Me.BindingSource1.EndEdit()
Dim bd As New OleDbCommandBuilder(ap)
ap.UpdateCommand = bd.GetUpdateCommand
ap.Update(Me.BindingSource1.DataSource)
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Private Sub ToolStrip_Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStrip_Cancel.Click '撤销操作
Button1_Click(sender, e)
End Sub
End class
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询