简体   繁体   English

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

[英]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. 我已经通过Visual Studio向导以vb形式DataGridView绑定了sql数据库表。
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. 我尝试了下面的代码,它成功执行并显示消息“已成功更新”,但实际上它并未对SQL数据库进行任何更改。 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. 我是VB.Net的新手,只有这件事阻止了我完成我的项目。 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 . 您需要将UpdateCommand添加到SqlDataAdapter You can do this manually in code, or you can configure a DataSet using the GUI in Visual Studio. 您可以通过代码手动执行此操作,也可以使用Visual Studio中的GUI配置数据集。

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 . 我建议从这里开始: https ://msdn.microsoft.com/zh-cn/library/ms254931(v = vs.110).aspx该文章中有9个子主题,您至少应完整阅读使用以下内容检索数据DataReader使用DataAdapter更新数据源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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