Search code examples
vb.netwinformscheckboxgroupbox

Set CheckBox Checked based on CheckBoxes of a GroupBox


Good Morning I want to ask something that is related in checkboxes I have to groups of checkboxes and it looks like this

enter image description here

My question is How can i check the checkbox Purchase Requisition whenever i check any checkbox in Group Purchase Requisition and if all of them are uncheck then checkbox Purchase Requisition is unchecked.

I have this code and I put this code on all of the checkbox inside Groupbox Purchase Requisition

  Sub check_Purchase_Req()
        Dim oCtl As Control
        Dim iX As Integer

        For Each oCtl In GroupBox3.Controls
            If TypeName(oCtl) = "CheckBox" And oCtl.Enabled = True Then iX = iX + 1

            If iX > 0 Then
                CheckBox1.Checked = True

            ElseIf CheckBox19.Checked = False And CheckBox20.Checked = False And CheckBox21.Checked = False And CheckBox22.Checked = False And CheckBox23.Checked = False Then

                CheckBox1.Checked = False
                Exit For
            End If
        Next
    End Sub

but this code doesnt meet what I need

Any help is appreciated TYSM


Solution

  • Here, Checkbox1 to Checkbox5 is the assumed named of the Checkboxes inside Purchase Requisition group box.

    chkPurchaseRequisition is also the Checkbox for your Purchase Requistion checkbox

    Try this one:

     Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
    CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged
        If sender.Checked = True Then
            chkPurchaseRequisition.Checked = True
        Else
            Dim AllUnchecked As Boolean = True
            For Each c As Control In grpboxPurchaseRequisition.Controls.OfType(Of CheckBox)()
                If DirectCast(c, CheckBox).Checked = True Then
                    AllUnchecked = False
                    Exit For
                End If
            Next
            If AllUnchecked = True Then
                chkPurchaseRequisition.Checked = False
            End If
        End If
    
    End Sub