从数据库中删除项目

时间:2013-12-10 18:32:05

标签: database vb.net

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    If lstDetails.SelectedItems.Count = 1 Then
        Dim Button = MessageBox.Show("Are you sure you want to delete this Data?", _
        "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)

        If Button = Windows.Forms.DialogResult.Yes Then
            Dim dt As New LoginSystemDataSet.AdministratorDataTable
            dt = AdministratorTableAdapter.DeleteQuery(lstDetails.SelectedItems(0).SubItems(0).ToString, lstDetails.SelectedItems(0).SubItems(0).ToString, lstDetails.SelectedItems(0).SubItems(0).ToString)
            lstDetails.Items.Remove(lstDetails.SelectedItems.Item(0))
        End If
    Else
        MsgBox("No items is selected", MsgBoxStyle.Critical)
    End If

End Sub

单击按钮时如何从数据库中删除记录。

1 个答案:

答案 0 :(得分:0)

您的AdminitratorTableAdapter类似乎已设置为执行DELETE操作。您应该单步执行代码并进行调试。

如果您想定期DELETE,请执行以下操作。将CAPS中的内容替换为与您的情况相关的值后。 ID字段也只是一个例子。您应该将其替换为lstDetails所选项目所代表的任何字段名称。

Dim dbCommand As SqlCommand
Dim strSQL As String

Using dbConnection as New SqlConnection("Data Source=YOUR_SQL_SERVER_NAME;Initial Catalog=YOUR_DB_NAME;Integrated Security=True")
    Try
        dbConnection.Open()
        strSQL = "DELETE FROM YOUR_TABLE_NAME WHERE ID = @ID"
        dbCommand = New SqlCommand(strSQL, dbConnection)
        dbCommand.Parameters.AddWithValue("@ID", lstDetails.SelectedItems.Item(0))
        dbCommand.ExecuteNonQuery()
        dbConnection.Close()
    Catch ex As Exception
        ' handle Exception, log it etc.
    End Try
End Using