4
 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 ?

8
  • I'm guessing this falls over when i = 0 ? Do you have a CheckBox0 on your form - again I'm guessing not. Have a look at the line <br> Dim c As CheckBox = CType(Me.Controls("CheckBox" & i.ToString), CheckBox) ... c is probably Nothing Commented Jan 30, 2013 at 11:43
  • Just tried debugging it for you and it fails for me on the Dim c as Checkbox line... can you post the asp code for your web form too? Commented Jan 30, 2013 at 11:46
  • don't have checkbox0 but i tried with [for loop] 1 To 2 & same result Commented Jan 30, 2013 at 11:48
  • @markp3rry this is the whole code Commented Jan 30, 2013 at 11:49
  • I mean the code from your web page - the html markup that has your controls on. Commented Jan 30, 2013 at 11:50

2 Answers 2

2

Try this:

For Each ctl In Me.Controls
  If TypeOf ctl Is CheckBox Then
   ctl.Enabled = b
  End If
Next
Sign up to request clarification or add additional context in comments.

1 Comment

ops, it works the reason is the checkboxes was in group box thank u ! ^
1

Two possible reasons. Your for-loop creates this control names:

  1. "CheckBox0"
  2. "CheckBox1"
  3. "CheckBox2"

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)

2 Comments

Works ! , Thank You , But could u explain what does ctrl(0) mean ? why the zero
@Zaid: I've commented it in my code snippet, ControlCollection.Find returns an array of controls. It is empty(Length=0) when no control was found with a given name as key. Since i assume that there is just one CheckBox with that name i've just taken the first. ctrl(0) gives me the first control in the control-array since arrays are zero based in .NET.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.