Reputation: 77
Public Class Form1
Private Function AllEnabled(ByVal b As Boolean) As Boolean
For i As Integer = 0 To 2
Dim c As CheckBox = CType(Me.Controls("CheckBox" & i.ToString), CheckBox)
c.Enabled = b
Next
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call AllEnabled(False)
End Sub
End Class
getting error with highlight in b
at c.Enabled = b
(Object reference not set to an instance of an object.)
but when i use checkbox1.enabled = b
instead of c.enabled = b
works fine.
so as i see the wrong not with b
right ?
& how can i fix this ?
Upvotes: 4
Views: 1336
Reputation: 16144
Try this:
For Each ctl In Me.Controls
If TypeOf ctl Is CheckBox Then
ctl.Enabled = b
End If
Next
Upvotes: 2
Reputation: 460158
Two possible reasons. Your for-loop creates this control names:
Maybe you want 1-3 or 0-1 instead.
Maybe you want to find your checkbox recursively, then you can use Find
:
For i As Integer = 0 To 2
Dim ctrl = Me.Controls.Find("CheckBox" & i.ToString, True)
If ctrl.Length <> 0 Then
ctrl(0).Enabled = b 'Find returns an aray'
End If
Next
Side-note: 2013 i would not use this VB6 style anymore:
Call AllEnabled(False)
but just
AllEnabled(False)
Upvotes: 1