How would one remove an item from a ListBox and then remove that line from the TextFile and repopulate the ListBox with new data in Visual Basic.Net?
My source(apparently you can't have StreamReader and StreamWriter accessing the same file at the same time):
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim FILE_NAME As String = "C:\TextFile.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek <> -1
If objReader.ReadLine = recordLine Then
lstListBox.Items.R开发者_JAVA技巧emoveAt(currentRecord)
numberOfRecords -= 1
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, False)
For i = 0 To numberOfRecords - 1
objWriter.WriteLine(lstListBox.Items(i))
Next i
objWriter.Close()
End If
Loop
lstListBox.Items.Clear()
numberOfRecords = 0
Do While objReader.Peek <> -1
lstListBox.Items.Add(objReader.ReadLine)
numberOfRecords += 1
Loop
objReader.Close()
Else
MsgBox("unknown error")
End If
End Sub
I'm very new to the VB.Net
Instead of StreamReader and StreamWriter you could just use FileStream and use a FileAccess type of ReadWrite. That way you can read and write at the same time.
It looks like the text file can be assumed to have the same lines as the listbox, since that is the way it ends up after this function. If that is the case, then you can delete the line from the listbox and then use it to write the text file.
Dim ss() As String
Dim i As Integer
Dim s As String
For Each s In ListBox1.Items
If s = recordLine Then
ListBox1.Items.Remove(s)
Exit For
End If
Next s
ReDim ss(ListBox1.Items.Count - 1)
For i = 0 To UBound(ss)
ss(i) = ListBox1.Items(i)
Next i
System.IO.File.WriteAllLines(FILE_NAME, ss)
If the listbox and text file can be different, then you can load the text file using ReadAllLines, remove the line from the array ss, then rewrite the text file using WriteAllLines.
精彩评论