Why does directcast of a string to an object result in 'object reference not set to an instance of an object'?

John Woo picture John Woo · Jun 23, 2011 · Viewed 11.7k times · Source

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.

Answer

Viv picture Viv · Jun 23, 2011

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