Marcel
Marcel

Reputation: 159

Object reference not set to instance of an object in VB.NET

Why am I getting the error "Object reference not set to instance of an object" with my code?

Public Class Form2
  Dim i As Integer = 0

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click
        Me.Close()
    End Sub

  Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPatient.Click

        Names(i) = txtPatientName.Text
        i = i + 1
  End Sub
End Class

Names() is a global variable

Thanks

Updated:

Module Module1
    Public Names() As String
    Public Heights() As Integer
    Public Weights() As Integer
End Module


Public Class Form2

    Dim i As Integer = 0

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click
        Me.Close()
    End Sub

    Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPatient.Click


        ReDim Preserve Names(0 To i)
        Names(i) = txtPatientName.Text

        ReDim Preserve Heights(0 To i)
        Heights(i) = txtPatientHeight.Text

        ReDim Preserve Weights(0 To i)
        Weights(i) = txtPatientWeight.Text

        i = i + 1

    End Sub
End Class

Upvotes: 1

Views: 2548

Answers (2)

user2990854
user2990854

Reputation:

If you insist on using a module, you should redim preserve your array.

Public Module Module1
    Public i As Integer = 0
    Public Names() As String
    Public Heights() As Integer
    Public Weights() As Integer
End Module

Public Class Form1
    Dim i As Integer = 0

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub

    Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


        ReDim Preserve Names(0 To i)
        Names(i) = txtpatientName.Text

        ReDim Preserve Heights(0 To i)
        Heights(i) = txtpatientheight.Text

        ReDim Preserve Weights(0 To i)
        Weights(i) = txtpatientweight.Text

        i = i + 1

    End Sub


    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        For Each j In Names
            MsgBox(j.ToString)
        Next

    End Sub
End Class

Upvotes: 1

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

You need to make module as public. So i suggest below

Public Module Module1
   Public Names() As String
   Public Heights() As Integer
   Public Weights() As Integer
End Module

Then access it in form like

Dim mod1 = Module1
mod1.Names(i) = txtPatientName.Text

Upvotes: 0

Related Questions