0

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
Ethan Malloy
  • 555
  • 1
  • 4
  • 16
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Peter Duniho Jul 06 '19 at 04:36
  • For arrays declared at the class level, use the `ReDim` keyword to allocate space and assign the reference to the field. Use `ReDim Preserve` to "resize" the array while keeping the contents. It's not quite as good as a list but it comes..."close". – madreflection Jul 06 '19 at 05:29
  • Oh, and `ReDim` takes the upper bound, not the length so, maddeningly, an array redimensioned with `-1` will have a `Length` of `0`. Yuck. – madreflection Jul 06 '19 at 05:37
  • 1
    Maybe you know what a `NullReferenceException` is, but you don't know how to fix it. How can be `CountyAndState.Length > 1`, when you have never initialized it? Use a `List(Of String)` as suggested and add items to it when required. `Clear()` it if you need to. The same goes for `YearlyIncome`. – Jimi Jul 06 '19 at 23:44

1 Answers1

1

I can see multiple problems with your code, but we'll focus on CountyAndState right now. First thing, it's declared as an array, but never initialized. An array is not dynamic. Are you familiar with pointers? Let me explain:

When you declare an array of 6 items, VB "reserve" enough space for 6 items on the stack. When you declare a list, VB "reserve" enough space on the stack to know where it will store the informations contained in the list, and store this information on the heap.

Your array is declared on the stack, so you need to inform VB of it's size beforehand. Since you never do it, you actually have no array. This is why you get a NullReferenceException: you look for the (non-existing) content of an array.

On the other, a List(Of String) would do what you want, and still be dynamic. Try initializing it like this: Dim CountyAndState As New List(Of String) and have fun!

laancelot
  • 3,138
  • 2
  • 14
  • 21