无法从DataGridView保存到SQL Server数据库VB.Net

时间:2015-04-13 04:05:05

标签: sql sql-server vb.net datagridview

我的数据从数据库成功显示到DataGridView,但当我在DataGridView中进行更改并单击表单代码中的更新按钮成功执行并显示消息“更新成功”...这意味着代码工作正常,但问题是更改没有保存在数据库中...当我重新加载表单时,它显示旧数据没有任何更改...这是我的代码

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"

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


End Class

1 个答案:

答案 0 :(得分:0)

我认为您错过了GetUpdateCommand()。如果错过了这行代码,则更新方法会失败。

尝试在cmdb1.GetUpdateCommand()之前添加da.Update(dt)

希望它有所帮助。