List Management in Visual Basic

Introduction: This tutorial is on how to create a simple tool in Visual Basic to manage lists and listboxes. Importing Lists: First we are going to write a function that will take a file input from the user which will hold a list of information (one per line). We will then make the function verify the file is there, and is not nothing/empty/null, followed by writing each line to a listbox...
  1. Private Function import()
  2.     Using fo As New OpenFileDialog
  3.         fo.Filter = "Text Files | *.txt" 'Set properties for OpenFileDialog, fo.
  4.         fo.FilterIndex = 1
  5.         fo.RestoreDirectory = True
  6.         fo.ShowDialog()
  7.         If (Not fo.FileName = Nothing And fo.CheckFileExists) Then
  8.             Using sr As New System.IO.StreamReader(fo.FileName) 'Create new streamreader to selected file
  9.                 While (sr.Peek <> -1) 'While not at end of file
  10.                     ListBox1.Items.Add(sr.ReadLine()) 'Add line to listbox
  11.                 End While
  12.             End Using
  13.         End If
  14.     End Using
  15. End Function
We then call the function from import button...
  1. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  2.     import()
  3. End Sub
Exporting Lists: Similarly to importing lists, we let the user select a saving text file, then use a new streamwriter (not streamreader like before) to write each item within the listbox to the file on a new line, using the .writeline function...
  1. Private Function export()
  2.     Using fs As New SaveFileDialog
  3.         fs.RestoreDirectory = True 'Set properties for savefiledialog, fs.
  4.         fs.ShowDialog()
  5.         If (Not fs.FileName = Nothing And fs.CheckFileExists And fs.CheckPathExists) Then
  6.             Using sw As New System.IO.StreamWriter(fs.FileName) 'Create new streamwriter to selected file
  7.                 For Each item As String In ListBox1.Items 'Iterate through listbox1.items
  8.                     sw.WriteLine(item) 'Write line
  9.                 Next
  10.             End Using
  11.         End If
  12.     End Using
  13. End Function
  14. <vb>
  15.  
  16. Again, call this from the export button...
  17.  
  18. <vb>
  19. Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
  20.     export()
  21. End Sub
Add & Remove: To add a new item to the listbox, we simply invoke the 'Add' function and parse it the string to add - in this case, textbox1's text...
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2.     ListBox1.Items.Add(TextBox1.Text)
  3. End Sub
Or we can also remove an item from a listbox by parsing the items index to the .'RemoveAt' function of a listbox...
  1. Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
  2.     ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
  3. End Sub

Add new comment