无法删除Listview项目

时间:2011-04-28 22:00:30

标签: vb.net winforms

我有一个Listview和一个这样的按钮

enter image description here

以下是我用于从Listview中删除数据的代码

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
    If lvNotesList.SelectedItems.Count > 0 Then
        Dim Result = MsgBox("Are sure you want to Delete the Selected Item ?", MessageBoxButtons.YesNo + vbQuestion)
        If Result = DialogResult.Yes Then
            Dim ID As String = lvNotesList.SelectedItems(0).SubItems(0).Text

            Try
                Dim sqlConnection As New SQLite.SQLiteConnection()
                Dim sqlCommand As New SQLiteCommand("", sqlConnection)
                Dim sqlPath As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
                Dim sqlQuery As String = "DELETE FROM Notes WHERE NoteID = " & ID
                sqlConnection.ConnectionString = sqlPath
                sqlConnection.Open()
                sqlCommand.CommandText = sqlQuery
                sqlCommand.ExecuteNonQuery()
                sqlConnection.Close()
                MsgBox("Operation Successfull", vbInformation)
            Catch ex As Exception
                MsgBox("Error: Operation Unsuccessfull." & Chr(13) & "Sumamry:" & ex.Message, vbExclamation)
            End Try

        Else
            Exit Sub
        End If
    Else
        MsgBox("Select an Item First", vbExclamation)
    End If
End Sub

由于某些原因,它会产生类似这样的错误

enter image description here

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

MsgBox会导致ListView失去焦点,从而清除选择。您必须将ListView的HideSelection属性设置为false

编辑:

试试这个

If lvNotesList.SelectedItems.Count > 0 Then
        Dim ID As String = lvNotesList.SelectedItems(0).SubItems(0).Text
        Dim Result = MsgBox("Are sure you want to Delete the Selected Item ?", MessageBoxButtons.YesNo + vbQuestion)
        If Result = DialogResult.Yes Then