空引用异常运行时错误

时间:2013-03-31 04:28:37

标签: vb.net nullreferenceexception

大家好我的项目中有一行代码得到一个空引用运行时错误,但是如果我断点它然后单步执行它一切正常。任何想法

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim checkbox_l As String = "CheckBox"
    Dim checkbox_i As string
    For i As Integer = 1 To id Step 1
        checkbox_i = checkbox_l + i.ToString
        Try
            If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
                My.Settings.name = Panel1.Controls("CheckBox" & i).Text
                Call installer_properties()
                Call start_install()
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    Next
End Sub

代码用于检查是否已选中动态创建的复选框,然后相应地继续,但是我在行中出错

If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then

2 个答案:

答案 0 :(得分:1)

使用Debug.Assert来捕捉它

Dim c as Control = Panel1.Controls(checkbox_i)
Debug.Assert(c IsNot Nothing)
Dim cb as CheckBox = TryCast(c, CheckBox)
If cb isNot Nothing Then
   If cb.Checked = True Then
      My.Settings.name = cb.Text
      Call installer_properties()
      Call start_install()
   End If
End If

答案 1 :(得分:0)

如果选中则获得结果1和0 - 如果不是,则可以写下:

textbox1.text = Microsoft.VisualBasic.Right(Panel1.Controls(" CheckBox"& i).ToString,1)