Click here to Skip to main content
15,896,500 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to delete datagridview with database in access 2003 using button & keyboard delete
my code
VB
Private Sub delete()
        Dim ds As New DataSet
        Dim da As New OleDbDataAdapter
        Dim cmd As New OleDbCommandBuilder


        con.Open()
        da = New OleDbDataAdapter("SELECT * FROm Part", con)
        cmd = New OleDbCommandBuilder(da)
        da.DeleteCommand = cmd.GetDeleteCommand()
        da.UpdateCommand = cmd.GetUpdateCommand()
        da.InsertCommand = cmd.GetInsertCommand()
        da.Fill(ds, "Part")
        DataGridView1.DataSource = ds.Tables("Part")

        Try
            Dim i As Integer = DataGridView1.SelectedRows(0).Index
            DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
            ds.Tables(0).Rows(i).Delete()
            da.Update(ds, "Part")
            MessageBox.Show("Success!")

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        con.Close()
    End Sub

when i click and delete by keyboard nothing happen n Error "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
Posted
Updated 1-Dec-11 19:52pm
v2
Comments
[no name] 2-Dec-11 1:53am    
EDIT: added emphasis on error

1 solution

VB
Try
For Each row As DataGridViewRow In DataGridView1.SelectedRows
ds.Tables(0).Rows(row.index).Delete()
Next
da.Update(ds, "Part")
DataGridView1.Refresh
MessageBox.Show("Success!")

By the way, your line:
VB
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
is obsolete, since you've got a bounded datagridview, a refresh will suffice.
 
Share this answer
 
v3
Comments
caello 2-Dec-11 2:37am    
Thanks for the attention
Now not error but nothing happen in my datagridview n database
Do you have any other way or other code
can you explain to me....
Scubapro 2-Dec-11 2:43am    
Sorry, I'm an 'Oracle man' and not quite Access orientated.
caello 2-Dec-11 3:44am    
Ok.. No problem

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900