Skip to content

Instantly share code, notes, and snippets.

@JamesVStone
Created April 16, 2018 21:50
Show Gist options
  • Save JamesVStone/a41ad4d3b4e6c8d62ad11ea37a6fbe7e to your computer and use it in GitHub Desktop.
Save JamesVStone/a41ad4d3b4e6c8d62ad11ea37a6fbe7e to your computer and use it in GitHub Desktop.
Homework 7- Mastering Arrays VB.net

Mastering Arrays

Arrays are like lists, or the ability to store multiple values in a single variable. For example, if you wanted to add scores or even just condence your code.

Visual Basic

In visual basic to create an array you must declare traditionaly with "Dim" but after the name you must specify how many items you want in your array (0 included).

Dim myName(1) As String

MyName(0) = "James" MyName(1) = "Stone"

Dim fullName As String = MyName(0) + ' ' + MyName(1)

Python

Arrays in python are more simple in the fact that you do not have to declare the amount of items in the the list. Arrays are marked by sqaure brackets [] with comma deliminated items. To call items by index (starting at 0) you put the

listName[0]

for the first item

 listName[1]

and so on Example:

myName = ["James", "Stone"]
fullName = myName[0] + ' ' + myName[1]

Index Errors

These usaly occur when you try and call an item that dose not exist from a list for example:

Dim myName(1) As String

myName(0) = "James" myName(1) = "Stone"

MessageBox.Show("Your name is: "& Myname(0)& ' ' & myName(1) & ' ' myName(2))

This would result in an error because there are only two items in this list.

Listboxes

To add items from arrays to listboxes you can add them individualy or you can use a for loop

Dim MyNumbers(4) As Integer

Dim i As Integer

MyNumbers(0) = 10 MyNumbers(1) = 20 MyNumbers(2) = 30 MyNumbers(3) = 40 MyNumbers(4) = 50

For i = 0 To 4

ListBox1.Items.Add(MyNumbers(i))

Next i

The next i statement add the end incremens i so the loop only repetes 4 times.

Assigning values to arrays

You can set a variable to parts of an array to be the value of something like a textbox

MyName(0) = Val(Textbox1.Text) MyName(1) = Val(Textbox2.Text)

this can make assignation alot easier

Arrays where the amount of items in not knowen

Instead of declaring a number of items you need you can leve the () after the variable name blank and have an undifined amount of items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment