Delete selected row from DataGridView and MS-Access Database

人盡茶涼 提交于 2021-02-10 15:04:55

问题


I am trying to delete the selected row from DataGridView and MS-Access database..

Private Sub ButtonEditDelete_Click(sender As Object, e As EventArgs) Handles ButtonEditDelete.Click

    If Not Connection.State = ConnectionState.Open Then
        Connection.Close()
    End If

    Try
        If Me.DataGridViewEdit.Rows.Count > 0 Then
            If Me.DataGridViewEdit.SelectedRows.Count > 0 Then
                Dim intStdID As Integer = Me.DataGridViewEdit.SelectedRows(0).Cells("Username").Value
                Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password="
                Connection.Open()
                Command.Connection = Connection
                Command.CommandText = "DELETE From MasterUser WHERE ID=? And Username=? And UserFullname=? AND Password=?"
                Dim res As DialogResult
                res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
                If res = DialogResult.Yes Then
                    Command.ExecuteNonQuery()
                Else : Exit Sub
                End If

                Connection.Close()
            End If
        End If
    Catch ex As Exception
    End Try
End Sub

回答1:


Replace your (Try) Part with this code:

   Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password=")
            cn.Open()

            Try
                For Each row As DataGridViewRow In DataGridViewEdit.SelectedRows
                    Using cm As New OleDbCommand
                        cm.Connection = cn
                        cm.CommandText = "DELETE * FROM CheckDJ WHERE [Username]= @myuser"
                        cm.CommandType = CommandType.Text
                        cm.Parameters.AddWithValue("@myuser", CType(row.DataBoundItem, DataRowView).Row("Username"))
                        cm.ExecuteNonQuery()
                    End Using
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

            cn.Close()
        End Using

then clear your datasource of datagridview by this line:

DataGridViewEdit.Datasource = nothing

then repeat the code part that is responsible of filling the datagridview from the database




回答2:


You are going about this in very much the wrong way. The proper way to do it would be to use an OleDbDataAdapter to populate a DataTable, bind that to a BindingSource and bind that to your DataDridView. You can then call RemoveCurrent on the BindingSource to set the RowState of the DataRow bound to the selected DataGridViewRow to Deleted. You then use the same OleDbDataAdapter to save the changes from the DataTable back to the database. The Fill method of the data adapter retrieves data and the Update method saves changes. You can call Update every time there's a change to save or you can let the user make all there changes locally first and then save them all in a single batch. Here's a code example:

Private connection As New OleDbConnection("connection string here")
Private adapter As New OleDbDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem",
                                      connection)
Private builder As New OleDbCommandBuilder(adapter)
Private table As New DataTable

Private Sub InitialiseDataAdapter()
    adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub

Private Sub GetData()
    'Retrieve the data.
    adapter.Fill(table)

    'Bind the data to the UI.
    BindingSource1.DataSource = table
    DataGridView1.DataSource = BindingSource1
End Sub

Private Sub SaveData()
    'Save the changes.
    adapter.Update(table)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    InitialiseDataAdapter()
    GetData()
End Sub

Private Sub deleteButton_Click(sender As Object, e As EventArgs) Handles deleteButton.Click
    BindingSource1.RemoveCurrent()
End Sub

Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
    SaveData()
End Sub

In certain circumstances, you may not be able to use an OleDbCommandBuilder and would have to create the InsertCommand, UpdateCommand and DeleteCommand yourself.



来源:https://stackoverflow.com/questions/62502653/delete-selected-row-from-datagridview-and-ms-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!