Hi, i cannot use this loop in vb.net, everytime I run it it will say that System.NullReferenceException: 'Object reference not set to an instance of an object.'

Duc Nguyen 101 Reputation points
2021-05-04T06:05:51.133+00:00

Public Class frmMenu

'define variables and constants for menu 

Const RegularPrice As Decimal = 8.5 'Can be easily changed if needed 

Const GourmetPrice As Decimal = RegularPrice + 5 

Dim OrderArray(11, 2) As String 'stored as name quantity price 



Public Sub populatemenu() 

    'store pizza names - Change names below when new pizza is added to menu 

    'Regular 

    OrderArray(0, 0) = "MARGHERITA" 

    OrderArray(1, 0) = "PEPPERONI" 

    OrderArray(2, 0) = "HAWAIIAN" 

    OrderArray(3, 0) = "HAM + CHEESE" 

    OrderArray(4, 0) = "TROPICAL VEGGIE" 

    OrderArray(5, 0) = "CLASSIC CHEESE" 

    OrderArray(6, 0) = "CHEESY GARLIC" 

    'Gourmet 

    OrderArray(7, 0) = "BBQ CHICKEN & BACON DELUXE" 

    OrderArray(8, 0) = "BUFFALO CHICKEN DELUXE" 

    OrderArray(9, 0) = "SUMMER SHRIMP DELUXE" 

    OrderArray(10, 0) = "HOT + SPICY MEAT DELUXE" 

    OrderArray(11, 0) = "SEAFOOD DELUXE" 



    'add prices to array 

    Dim i As Integer 

    For i = 0 To 6 

        OrderArray(i, 2) = RegularPrice 

    Next 

    For i = 7 To 11 

        OrderArray(i, 2) = GourmetPrice 

    Next 



    'add names to menu 

    For i = 1 To 12 

        Dim myLabel As Label = CType(Me.Controls("lblpizza" & i), Label) 

        myLabel.Text = i & " " & OrderArray(i - 1, 0) 

    Next 

    'add prices in a similar way to above but format according to this (item.ToString("C")) 



    For i = 12 To 18 

        Dim myLabel As Label = CType(Me.Controls("Label" & i), Label) 

        myLabel.Text = RegularPrice.ToString("C") 

    Next 

    For i = 19 To 23 

        Dim myLabel As Label = CType(Me.Controls("Label" & i), Label) 

        myLabel.Text = GourmetPrice.ToString("C") 

    Next 



End Sub 

End Class

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,570 questions
{count} votes

6 answers

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-05-06T06:57:44.85+00:00

    Hi anonymous user ,
    You need to name your labels 'lblpizza1','lblpizza2'...'lblpizza12' to avoid the exception.
    Besides, check the following reference about the error.
    Error inside of Application.Designer.vb inside of OnCreateMainForm() Sub

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments