
Removing an item from a ListView
I have a function to remove items in a ListView (called ListView1) when
a user presses the Delete key, as shown below.
I have a Test.txt file that contains the data I want listed in my
ListView. I can successfully read this into the ListView using a
FileStream and StreamReader, with both the FileStream and StreamReader
closed upon completion of populating the ListView. The application then
sits idle waiting for the user to add to or remove items from the
ListView. Adding items is easy, but removing items is proving
difficult.
My problem is that when I select an item in the ListView and press the
Delete key on the keyboard, the ListViewItem correctly disappears from
the ListView but when it should write the shortened ListView contents to
the Test.txt file, it doesn't change anything in the Test.txt file. If
I display the items that should be written to the text file by popping
them up in a message box, it seems like the correct data is going to be
written to the file. When the function is finished, I check the
Test.txt file to see if the items have been correctly written to the
file, but I find the original ListView contents listed, and sometimes
some half completed ListViewItem strings added to the end of the list.
I have tried using the Flush() function to clear the FileStream and
StreamWriter buffers but this seems to have no effect.
It seems trivial to me how writing the contents of a ListView to file
after having an item removed can go wrong, but I can't seem to solve the
problem.
Please help!
Jules
p.s. I appreciate this is not the most efficient way to code the
function, I would put the file writing part of the function as a
separate function and call it when required... but this is how I want it
for the moment
--------------------------------
Public Sub ListView1_KeyDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = System.Windows.Forms.Keys.Delete Then
If ListView1.SelectedItems.Count() <> 0 Then
'I actually want files to be removed one by one..
'I know how to iterate through the SelectedItems Array!
Dim removeItemIndex As Integer =
ListView1.SelectedItems.Item(0).Index()
ListView1.Items.RemoveAt(removeItemIndex)
ListView1.Refresh()
Dim fs As New System.IO.FileStream("C:\Playlists\Test.txt",
System.IO.FileMode.OpenOrCreate)
Dim sw As New System.IO.StreamWriter(fs)
fs.Flush() = True
sw.Flush() = True
Dim r As Integer
For r = 0 To ListView1.Items.Count - 1
'MsgBox(ListView1.Items.Item(r).Text)
sw.WriteLine(ListView1.Items.Item(r).Text)
Next r
sw.Close()
fs.Close()
End If
End If
End Sub
--------------------------------
*** Sent via Developersdex http://www.*-*-*.com/ ***
Don't just participate in USENET...get rewarded for it!