crackruckles crackruckles - 6 months ago 15
Vb.net Question

Null Reference Exception Run Time Error

Hi all im getting a null reference run time error with one line of code in my project, however if i break point it and then step through it everything works fine. Any Thoughts

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


The code is meant to check if a dynamically created checkbox has been checked and then move on accordingly, however im getting an error with the line

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

Answer

Use Debug.Assert to catch it

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