简体   繁体   English

如何从Visual Basic 2013 .net中的DataGridView更新SQLite数据库?

[英]How to update SQLite database from DataGridView in Visual Basic 2013 .net?

I am displaying data from SQLite table into a DataGridView as following - 我正在将数据从SQLite表显示到DataGridView中,如下所示-

Private Sub Subjects_Manager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        con = New SQLiteConnection("Data Source = c:\demo\test.db;Version=3;")
        con.Open()
        sql = "SELECT * FROM med_subjects"
        da = New SQLiteDataAdapter(sql, con)
        da.Fill(ds, "SubjectsList")
        DataGridView1.DataSource = ds.Tables("SubjectsList").DefaultView
        With DataGridView1
            .RowHeadersVisible = False
            .Columns(0).HeaderCell.Value = "Subject Id"
            .Columns(1).HeaderCell.Value = "Subject Name"
        End With
        DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
        con.close()
End Sub

I want to save changes done in DataGridView (either Updation of Row/s or Insertion of Row/s) back to SQLite table . 我想将在DataGridView中完成的更改(行/秒的更新或行/秒的插入)保存回SQLite表 But I couldn't find a way to do so. 但是我找不到办法。

Edit 1 : I know Insert/Update Queries of SQLite, but what I don't know is how & where to keep them so that they can be triggered in responses to changes made in DataGridView. 编辑1:我知道SQLite的插入/更新查询,但我不知道如何以及在哪里保留它们,以便可以在对DataGridView中所做的更改的响应中触发它们。 eg 例如

' I am using this variable for demonstration, in reality InsertSubjectSqlString will be equal to changes done in DataGridView

Dim InsertSubjectSqlString As String = "Insert into med_subjects (Subject_Name) Values ('_Miscellaneous')"
Dim SqliteInsertRow As SQLiteCommand
SqliteInsertRow = con.CreateCommand
SqliteInsertRow.CommandText = InsertSubjectSqlString
SqliteInsertRow.ExecuteNonQuery()

But I don't know, where should I put it? 但是我不知道该放在哪里?

Edit 2: After seeing comments and answers, I came to know that there is No direct way to Insert/Update Sqlite database from DataGridView. 编辑2:看到评论和答案后,我知道没有直接方法可以从DataGridView插入/更新Sqlite数据库。 So I was curious, if there is any event like RowSelected which would 所以我很好奇,是否有像RowSelected这样的事件

  • trigger on selecting a row and get that row's data 在选择一行时触发并获取该行的数据
  • then taking the row's data into multiple text boxes and lastly 然后将行的数据放入多个文本框,最后
  • triggering Insert/Update queries taking values from these textboxes by a button 触发通过按钮从这些文本框中获取值的插入/更新查询

I know it's highly hypothetical with NO sample codes, but it's because I am asking for Event name. 我知道没有任何示例代码是高度假设,但这是因为我要求提供事件名称。

Call this on LeaveRow event or CellEndEdit 在LeaveRow事件或CellEndEdit上调用它

  Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
 Dim i as integer
 Try
 for i = 0 to datagrid.rows.count-1
      myUpdate(datagrid.item(0,i).tostring() , datagrid.item(1,i).tostring())
 next
 Catch ex As Exception
 MsgBox(Err.Description)
 End Try
 End Sub

note , you can also give the column name of your grid in place of column index , like this datagrid.item("fname",i).tostring() 注意,您也可以使用网格的列名代替列index,例如datagrid.item(“ fname”,i).tostring()

Here we will save in database: 这里我们将保存在数据库中:

  Sub myUpdate(byval fname as string , byval lname as string)
Try
 dim con as new sqlconnection("you connection string")
 dim cmd as new sqlcommand
      con.open()
      cmd.connection= con
      cmd.commandtext="insert into table (fname,lname) values (@fname,@lname)"
      cmd.Parameters.AddWithValue("@fname", fname)
      cmd.Parameters.AddWithValue("@lname", lname)
      cmd.ExecuteNonQuery()
      Con.close()
      Catch ex As Exception
      MsgBox(Err.Description)
      End Try
 End sub

I hope this will help you to solve ! 希望这可以帮助您解决!
There are many ways to manipulate data . 有许多方法可以处理数据。
CristiC CristiC

I dont think you will find some magic way that the DataGridView and DataTable are going to persist things automatically to the backend SQLite database. 我认为您不会发现DataGridView和DataTable会自动将事物持久化到后端SQLite数据库的一种神奇方法。 As you are hinting at I think you will have to rely on events. 正如您所暗示的,我认为您将不得不依靠事件。

I think the event you are missing is answered here stackoverflow cell value changed event 我认为您所缺少的事件已在此处回答stackoverflow单元值更改事件

Ok I think is better to use CellEndEdit, because LeaveRow is triggered only if you click on other row. 好的,我认为最好使用CellEndEdit,因为仅当您单击另一行时才会触发LeaveRow。
Look on this example. 看这个例子。
you must 你必须
use: da.Update(ds.Tables("SubjectsList").DefaultView) 使用: da.Update(ds.Tables(“ SubjectsList”)。DefaultView)

 Imports System.Data.SqlClient

Public Class Form1 公开课表格1

Const connectionstring As String = "server=(local);database=TestDB;uid=sa;pwd=sa;"
Private SQL As String = "select * from customer"
Private con As New SqlConnection(connectionstring)
Private dt As New DataTable
Private adapter As New SqlDataAdapter(SQL, con)
Private commandbuilder As New SqlCommandBuilder(adapter)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    adapter.Fill(dt)
    DataGridView1.DataSource = dt
End Sub

Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
    adapter.Update(dt)
End Sub

End Class 最终班

Please use this code hopefully it will work 请使用此代码,希望它能正常工作

Imports System.Data.SQLite

Public Class Form       
Dim con As New SQLite.SQLiteConnection
        Dim da As New SQLite.SQLiteDataAdapter
        Dim dt As New DataTable
        Dim cmdbl As New SQLite.SQLiteCommandBuilder
        Dim dlgResult As DialogResult     

        Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
             dlgResult = MessageBox.Show("Do you want to save the changes you made?", "Confirmation!", MessageBoxButtons.YesNo)
                            If dlgResult = DialogResult.Yes Then
                                Try
                                    con.Open()
                                    cmdbl = New SQLiteCommandBuilder(da)

                                    da.Update(dt)
                                    MsgBox("Updated successfully!")
                                    con.Close()
                                Catch ex As Exception
                                    MsgBox(ex.ToString)
                                End Try

                            End If
    End Sub
End Class

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

相关问题 如何从Visual Basic中的DataGridView更新Access DB - How to update an Access DB from a DataGridView in Visual Basic 如何使用Visual Basic .net从Datagridview获取列(“ id”)值 - How to get column (“id”) value from datagridview with visual basic .net 在 VB.NET (Visual Studio 2013) 中使用 OLEDB 通过 DataGridView 更新访问数据库的按钮 - Update Button for Access Database via DataGridView Using OLEDB in VB.NET (Visual Studio 2013) visual basic.net 2013数据库Ms Access 2013 - visual basic.net 2013 database Ms Access 2013 我如何使用visual basic .net从同一个访问数据库更新不同的表 - How do i update different table from the same access database using visual basic .net 如何在Visual Basic(.NET)中绑定到MySQL数据库的datagridview上实现自动刷新 - How to implement an auto refresh on a datagridview bound to a MySQL database in Visual Basic (.NET) VB 2013:如何使用datagridview值更新数据库 - VB 2013: how to update database using datagridview values 如何在Visual Basic 2010 DataGridview中填充Sql数据库? - How do i populate a Sql database in a Visual Basic 2010 DataGridview? 如何在Visual Basic 2013(.net)中自动调整水平对齐的面板的大小 - How to auto resize horizontally aligned panels in Visual Basic 2013 (.net) 如何在ListView Visual Basic网上显示数据库 - how to show database on listview visual basic net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM