如何通过单击按钮更新DataGridView中的数据来更新数据库?

时间:2015-04-17 09:08:57

标签: vb.net datagridview sql-update

我通过Visual Studio向导使用vb格式的DataGridView绑定了sql数据库表。
我尝试了下面的代码,它成功执行并显示消息“已成功更新”,但实际上它不会对SQL数据库进行任何更改。当我重新加载表单时,我没有看到任何变化。我是VB.Net的新手,只有这件事阻止我完成我的项目。请帮忙...提前致谢

Imports System.Data.SqlClient

Public Class FormUpdate

'Variables declared here
Dim Con As New SqlConnection
Dim Cmd As New SqlCommand
Dim ds As DataSet
Dim da As New SqlDataAdapter
Dim cmdString As String
Dim dt As New DataTable
Dim dr As SqlDataReader
Dim cmdbl As New SqlCommandBuilder

Public Sub FormUpdate_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'TODO: This line of code loads data into the 'ShipmentDataSetDataGridView.Shipment_Main' table. You can move, or remove it, as needed.
    Me.Shipment_MainTableAdapter2.Fill(Me.ShipmentDataSetDataGridView.Shipment_Main)

 'CONNECTION STRING FOR THE DATABASE
    Con.ConnectionString = "Data Source=TARIQUE;Initial Catalog=shipment;Integrated Security=True"
End Sub

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click

Try
   Con.Open()
   cmdbl = New SqlCommandBuilder(da)
   da.Update(dt)
   MessageBox.Show("Updated successfully!")
Catch ex As Exception
       MessageBox.Show(ex.ToString)

End Try
   Con.Close()
End Sub

1 个答案:

答案 0 :(得分:0)

您需要向UpdateCommand添加SqlDataAdapter。您可以在代码中手动执行此操作,也可以使用Visual Studio中的GUI配置DataSet。

看起来您可以从阅读文档中受益。我建议从这里开始: https://msdn.microsoft.com/en-us/library/ms254931(v=vs.110).aspx 该文章中有9个子主题,您应该至少完全阅读 使用DataReader检索数据 使用DataAdapters更新数据源