Dan Hayes
Dan Hayes

Reputation: 97

vb.net creating a label using a class

I am new to using classes and OOP. I have created a class that will create a new label every time it is called. here is my code:

Public lbl As New Label
Public txt As New TextBox
Public controls As List(Of Control)
Public Sub New()
    'Add a label

    lbl.Name = "Label" & 1
    lbl.Text = "Student " & 1 & ":"
    lbl.Size = New Size(65, 20)
    lbl.Location = New Point(10, (10 * 22) + 5)

    controls.Add(lbl)
End Sub

When i call this class i get this error message:

An unhandled exception of type 'System.NullReferenceException' occurred in Project.exe    Additional information: Object reference not set to an instance of an object.

The line of code the message highlights is:

controls.Add(lbl)

Any help would be appreciated, thanks.

Upvotes: 1

Views: 1272

Answers (1)

Zeddy
Zeddy

Reputation: 2089

Public lbl As New Label
Public txt As New TextBox
Public controls As List(Of Control)

Public Sub New()
  'Add a label

  lbl.Name = "Label" & 1
  lbl.Text = "Student " & 1 & ":"
  lbl.Size = New Size(65, 20)
  lbl.Location = New Point(10, (10 * 22) + 5)
  If (controls is nothing) = True Then controls = new list(of Control)
  controls.Add(lbl)
End Sub

Upvotes: 1

Related Questions