简体   繁体   中英

How can i update database by updating data in DataGridView by a button click?

I have bounded sql database table with vb form DataGridView through Visual studio wizard.
I tried below code and it executes successfully and show message "Updated Successfully" but in reality it does not makes any changes to SQL Database. When i reload the form i am not seeing any changes. I am new to VB.Net and only this thing is resisting me to complete my project. Please help...Thanks in advance

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

You need to add an UpdateCommand to your SqlDataAdapter . You can do this manually in code, or you can configure a DataSet using the GUI in Visual Studio.

It looks like you could benefit from reading the documentation. I would recommned starting here: https://msdn.microsoft.com/en-us/library/ms254931(v=vs.110).aspx There are 9 subtopics in that article, and you should fully read at least Retrieving Data Using a DataReader and Updating Data Sources with DataAdapters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM