EDIT: I already know what a null reference exception is. What I can't figure out is how to set up my code so that it reads the length of an empty array without throwing a null reference exception.
I have a form that needs to add an item to a set of parallel arrays each time the "submit" button is clicked. I need a way of making sure the index increments, so I've written the code so that it gets the length of one array and subtracts 1 to get the index, stored in a variable. However, for the first item in the array, I keep getting a null reference error: 'Object reference not set to an instance of an object.'
I'm not sure what to do, as the arrays are defined at the class level and can't have any values until something gets added to them. I can't just tell it what the value at myArray(0)
is, because that would be overwritten each time the user clicks "submit." How can I get this to work? Thanks for any help :)
Here is my code:
Option Strict On
Public Class frmMain
'Declare arrays to store data
Dim CountyAndState() As String
Dim YearlyIncome() As Double
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'Validate inputs and assign data to arrays
'Reset colors for inputs
cboCountyState.BackColor = Color.White
txtYearlyIncome.BackColor = Color.White
'Declare variables
Dim strResidence As String
Dim dblIncome As Double
Dim intIndex As Integer
'Validate input
If Validation(CStr(cboCountyState.SelectedItem), txtYearlyIncome.Text) = True Then
'Assign values to variables
dblIncome = CDbl(txtYearlyIncome.Text)
strResidence = CStr(cboCountyState.SelectedItem)
'Get index for new array item
If CountyAndState.Length > 1 Then '*****THIS IS WHERE THE ERROR OCCURS******
intIndex = (CountyAndState.Length - 1)
Else
intIndex = 0
End If
'Add items to arrays
CountyAndState(intIndex) = strResidence
YearlyIncome(intIndex) = dblIncome
MessageBox.Show(CountyAndState(intIndex))
End If
End Sub