Freshman Freshman - 5 months ago 12
Vb.net Question

Button to delete line from combobox which is stored in a .dat file

I'm making a tiny internal database which is used to store the content of a combobox (it is supposed to be administrated from the program, wich is why I choose to do it this way) I want two small side programs that's supposed to manage the content of this little database; one to add content(a line) and a second to remove content(a line) from the .dat file.

The first one was simple:

Dim nyUtvidelse As String
nyUtvidelse = TextBox1.Text
My.Computer.FileSystem.WriteAllText("C:\database.dat", vbCrLf + nyUtvidelse, True)


Here comes the problem, with the remove function:
This is on MyBase.load:

cmboxType.Items.Clear()
cmboxType.Items.AddRange(IO.File.ReadAllLines("C:\database.dat"))


From this ComboBox I want to be able to select a line in the database for deletion with the click of a button. I'm not quite sure how to do this; alter
C:\database.dat
based upon the selection in cmboxType.

Answer

Read all lines into an array, then populate the combo box with the array. When you click delete, grab the combobox selected index and ignore that array element when writing the array back to the file.

Dim lines As String()

Private Sub load_combo()
    lines = System.IO.File.ReadAllLines("C:\database.dat")
    cmboxType.Items.Clear()
    cmboxType.Items.AddRange(lines)
End Sub

Private Sub delete_item()
    Dim sw As New System.IO.StreamWriter("C:\database.dat")
    For i As Integer = 0 To lines.Length - 1
        If i <> cmboxType.SelectedIndex Then
            sw.WriteLine(lines(i))
        End If
    Next
    sw.Close()
End Sub