Vb.net – Why does directcast of a string to an object result in ‘object reference not set to an instance of an object’

directcastvb.net

I am trying to cast a string into an object (which is a parameter of a procedure). I also tried Ctype but it didn't work.

Public Sub procName(lbl1 as Label, lbl2 as Label, lbl3 as Label) 'suppose I have 10 labels
       
      'long code here
       
       for i as integer = 1 to 3
            dim xL as label = DirectCast(Controls("lbl" & i.ToString), Label)
            xL.text = i.Tostring    'I get the error here
       next

End Sub

The error is:

Object reference not set to an instance of an object.

Best Answer

DirectCast(Controls("lbl" & i.ToString), Label) is giving out a null value (or nothing)

What does Controls("lbl" & i.ToString) return? is it of type label?

I don't have VB installed, so I cannot verify the following code:

For i as integer = 1 to 3 
    For Each acontrol As Control In Controls
       If acontrol.Name = "lbl" & i.ToString Then
           xL.text = i.Tostring
       End If
   Next
Next
Related Topic