我有这个功能工作正确。正确工作的部分是我可以在DataGridView上选择一行的位置,使用“Delete Row”按钮调用此函数,然后它将从DataGridView中删除该行....但是,它不会删除行在数据库上。使用OleDb从数据库删除行
任何人都可以帮我从数据库中删除行使用OleDb?
Function DeleteTableRow()
Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
Dim dbConnection = New OleDbConnection(TaxConnStr)
Try
Dim dbCommand As OleDbCommand = New OleDbCommand
Dim rdr2 As OleDbDataReader
Dim selectedRow = DataGridView1.SelectedRows
dbCommand.CommandText = "DELETE FROM UserCriteria WHERE RowID =" & selectedRow
If dbConnection.State = ConnectionState.Closed Then
dbConnection.Open()
End If
dbCommand.Connection = dbConnection
rdr2 = dbCommand.ExecuteReader
dbCommand.ExecuteNonQuery()
rdr2.Close()
'''Must select entire row to delete
'DataGridView1.Rows.Remove(DataGridView1.Rows(DataGridView1.SelectedCells.Item(0).RowIndex))
'''allows you to select on cell in the row to delete entire row
For Each oneCell As DataGridViewCell In DataGridView1.SelectedCells
If oneCell.Selected Then
DataGridView1.Rows.RemoveAt(oneCell.RowIndex)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
dbConnection.Close()
End Try
End Function
更正---数据库中的列名称就是“ID”。另外,在DataGridView中,我将此列(“ID”列)设置为隐藏。这是一个问题吗? – MaylorTaylor 2013-03-27 17:16:19
不,只是改变代码来反映这一事实。我将更新答案 – Steve 2013-03-27 17:17:44
您的For循环似乎不正确。我有“对于Datagridview1.selectedrows中的每个selectedRow”... ... – MaylorTaylor 2013-03-27 17:21:36