0

I'm doing an assignment for Uni and in my VB.NET form I have some checkboxes, I'm trying to loop through and clear them (I have a button which will clear the form)

My problem is that there seems to be no property I can use to set the state of a checkbox when not explicitly telling VB which checkbox I want to use. for example, I can go

WineCheckBox.Checked = False

That will check the box, but I wand to DRY the code up a bit and not have to repeat this for each check box I have, this is what I was trying to do:

If TypeOf element Is CheckBox Then
    element.Checked = False
End If

I've tried using element.CheckState and element.Checked and both times I get "Checked (or CheckState) is not a member of System.Windows.Forms.Control"

I've looked through all the attributes that I can find for this and none of them seem of use to me...

Am I missing something? or is this just not possible to do

Thanks

EDIT:

this is the whole block of code:

'clear the controls
    For Each element As Control In Me.Controls
        If TypeOf element Is TextBox Then
            element.Text = ""
        End If
        If TypeOf element Is CheckBox Then
            element.Checked = False
        End If
    Next

2 Answers 2

8

What type have you declared element as? If its just a Control then this is a base type for CheckBox that doesn't have the checked property. Maybe try:

If TypeOf element Is CheckBox Then
    DirectCast(element,CheckBox).checked = False
End If
1
  • I'd recommend you use DirectCast since it is only CheckBoxes or derived controls that will evaluate to True. This circumvents the added overhead of using CType as it sometimes has to coerce values into a different type. See this answer to one of my earlier questions (Casting DataTypes with DirectCast, CType, TryCast). Commented Mar 20, 2011 at 13:43
2

How about:

   For Each element As Control In Me.Controls
        If TypeOf element Is TextBox Then
            element.Text = ""
        End If
        If TypeOf element Is CheckBox Then
            Dim chk As CheckBox = CType(element, CheckBox)
            chk.Checked = False
        End If
    Next

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.