Visual Basic Lists
In Visual Basic, lists are very similar to Arrays. A list contains a group of separate data all contained in one place. The type of data that can be stored within a list can be any type of variant. However, only one type can be contained within one list.
Creating a new List
Dim is the keyword inside Visual Basic which creates a new instance of a variable.
Following the keyword Dim we have the variable name of our new list which can be changed accordingly and is used to reference to the list later on in our project.
Dim ourList As New List
Here we are setting the variable type of ourList to a new instance of a list.
Dim ourList As New List(Of String)
Finally, we have already set the type of our variable in Step 3 so here we are setting the type of variable go within our new List.
In summary, we have a new variable called ourList which is set equal to a new list of strings.
Adding and Clearing a List
Once we have created our list we can simply add items to it by simply using the Add function. Because we set our type of our list to a string, the add function will only accept a string type:
ourList.Add("Item To Add")
If we require to empty our list of all entered values, we can use the clear function:
Getting or Setting a variable within a List
We can write a simple line of code to give us the value of a part of a list and output it in a simple messagebox, like so:
This code would create a msgbox with the message set to the value of ourList(1). This will return the value which we have added second to our List. Why Second? Because the List begins counting at 0, so 1 is actually 2.
To set a new value to a variable within our list we can use the assignment operator:
ourList(1) = "Hello World!"