List Management in Visual Basic
Submitted by Yorkiebar on Monday, April 21, 2014 - 10:51.
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...
We then call the function from import button...
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...
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...
Or we can also remove an item from a listbox by parsing the items index to the .'RemoveAt' function of a listbox...
- Private Function import()
- Using fo As New OpenFileDialog
- fo.Filter = "Text Files | *.txt" 'Set properties for OpenFileDialog, fo.
- fo.FilterIndex = 1
- fo.RestoreDirectory = True
- fo.ShowDialog()
- If (Not fo.FileName = Nothing And fo.CheckFileExists) Then
- Using sr As New System.IO.StreamReader(fo.FileName) 'Create new streamreader to selected file
- While (sr.Peek <> -1) 'While not at end of file
- ListBox1.Items.Add(sr.ReadLine()) 'Add line to listbox
- End While
- End Using
- End If
- End Using
- End Function
- Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
- import()
- End Sub
- Private Function export()
- Using fs As New SaveFileDialog
- fs.RestoreDirectory = True 'Set properties for savefiledialog, fs.
- fs.ShowDialog()
- If (Not fs.FileName = Nothing And fs.CheckFileExists And fs.CheckPathExists) Then
- Using sw As New System.IO.StreamWriter(fs.FileName) 'Create new streamwriter to selected file
- For Each item As String In ListBox1.Items 'Iterate through listbox1.items
- sw.WriteLine(item) 'Write line
- Next
- End Using
- End If
- End Using
- End Function
- <vb>
- Again, call this from the export button...
- <vb>
- Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
- export()
- End Sub
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- ListBox1.Items.Add(TextBox1.Text)
- End Sub
- Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
- ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
- End Sub
Add new comment
- 23 views