Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object reference not set to an instance of an object" Trying to add to list

Tags:

vb.net

I've created A list of object "emails" which contains the "email" object which has 3 parameters (String Address, String Subject, String Body)

I then want to add to the list by creating more instances of "email". However, I've tried so many different ways and it's having none of it.

Public Class Test

   Public emails As List(Of Email)

   Private Sub Test_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

      emails(0).setAddress("Hello")
      emails(0).setSubject("World2")
      emails(0).setBody("Why don't you work?")
      emails.Add(New Email("Hello2", "World2", "Why don't you work?2"))

   End Sub

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Label1.Text = emails(0).getAddress
       Label2.Text = emails(0).getSubject
       Label3.Text = emails(0).getBody

       Label4.Text = emails(1).getAddress
       Label5.Text = emails(1).getSubject
       Label6.Text = emails(1).getBody
   End Sub
End Class

If I click button1 I get the error "Object reference not set to an instance of an object".

Thanks.

like image 656
Hypergiant Avatar asked Dec 19 '11 02:12

Hypergiant


People also ask

How do I fix object reference not set to an instance of an object?

To fix "Object reference not set to an instance of an object," you should try running Microsoft Visual Studio as an administrator. You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version.

What causes object reference not set to an instance of an object?

The message "object reference not set to an instance of an object" (NullReferenceException) means that you are referring to an object the does not exist or was deleted or cleaned up. In order to prevent the error, objects that could be null should be tested for null before being used.


1 Answers

You have not created an instance of the list, you have only declared it.

 Public emails As New List(Of Email) 
 '                ^^^
like image 182
Anthony Pegram Avatar answered Sep 27 '22 02:09

Anthony Pegram