1

I have a Listview and a button like this

enter image description here

Below is the code I have used for deletion of Data from 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

For some Reason it produces an Error like this

enter image description here

How can I fix this ?

1 Answer 1

2

The MsgBox causes the ListView to lose focus which in turn clears the selection. You'll have to set HideSelection property of your ListView to false.

EDIT:

Try this

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it works perfect when I remove the msgbox. But then how can I warn the user ?
set HideSelection to false for your listview from the designer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.