CheckBoxes created in code

martin.s.ransome

Active member
Joined
May 29, 2011
Messages
25
Programming Experience
5-10
I have created all the controls in my app in vb.net code. I have checkboxes that I want to be able to check the state in code and also check or uncheck if i need to this is my code which does not work
VB.NET:
        Dim objControl As Control


        For Each objControl In Me.Controls
            If TypeOf objControl Is CheckBox Then
                objControl.checkstate = CheckState.Checked
            End If
        Next

checked is not a property of of the the control class.
Error 1 'checkstate' is not a member of 'System.Windows.Forms.Control'.

Please share your wisdom.

Everyday I realize how very little I know.
 
I think you are looking for the checked property

VB.NET:
        For Each objControl In Me.Controls
            If TypeOf objControl Is CheckBox Then
                objControl.checked= true
            End If
        Next
 
Cast the control object to appropriate type using DirectCast or CType.

You can also filter the controls by type like this:
For Each cb In Me.Controls.OfType(Of CheckBox)()
    cb.Checked = True
Next

'cb' loop variable here is inferred and typed Checkbox, by the way.
 
Your profile says .NET 3.5. Is that indeed the version your project is targeting? If not then that code will not work. If so then that code will work, assuming the appropriate references and imports. Those references and imports should be provided by default for a Windows Forms project created in VS 2008 or VS 2010 but you can check to make sure. Your project would need to reference System.Core.dll and you will also need to import, either at the file level or, preferably, at the project level, the System.Linq namespace.
 
I came up with the following code with some of the suggestions made here and from http://www.codeproject.com/KB/dotnet/CheatSheetCastingNET.aspx.

VB.NET:
        Dim objControl As New Control
        Dim chBox As CheckBox


        For Each objControl In Me.Controls
            If TypeOf (objControl) Is CheckBox Then
                If objControl.Name = "chkBox_3" Then
                    chBox = DirectCast(objControl, CheckBox)
                    chBox.Checked = True
                End If
            End If
        Next
[CODE]
 
Back
Top