开发者

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

开发者 https://www.devze.com 2023-03-15 10:22 出处:网络
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.

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 ob开发者_运维技巧ject.


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


As Vivek points out, xL is Nothing. for your given i, i.ToString() cannot throw Null Reference Exception.

Try

for i as integer = 1 to 3
    dim xL as label = DirectCast(Controls("lbl" & i.ToString), Label)
    If xL IsNot Nothing
        xL.text = i.Tostring    
    End If
next


The code you're showing expects to find three Label controls on your form (or at least within the scope of the code being run), named lbl1, lbl2 and lbl3.

The error is telling you that one or more of these controls cannot be found.


Rather than passing 3 different Labels how about you pass a List of labels and iterate through it. This way it will make your function more dynamic and cleaner.

Public Sub procName(ByVal labels As List(Of Label))

        Dim i As Integer = 1

        For Each lbl As Label In labels

            Dim xL As Label = lbl

            xL.Text = i.ToString

            i += 1
        Next

End Sub


I needed to do something similar, and I was getting the same error,

(Object reference not set to an instance of an object.

on a similar line like:

dim xL as label = DirectCast(Controls("lbl" & i.ToString), Label)

I was able to fix it by adding to the Controls the exact location of where the control is, in my case TabPage3:

dim xL as label = DirectCast(TabPage3.Controls("lbl" & i.ToString), Label)

and voilà, IT WORKED!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号