I have a question,,,

I create 1 form, and in this form I add 5 control checkbox, namely:
Checkbox1 = cek1
Checkbox2 = cek2
Checkbox3 = cek3
Checkbox4 = cek4
Checkbox5 = cek5

I want to ask,
1. how to count the number of checkboxes are checked.?
2. how to / code to display cekbox anywhere in check.? for example:
if I choose cek1 and cek2, the message "You Choose Cek1 and Cek2"
if I choose cek2 and cek3, the message "You Choose Cek2 and Cek3"
if I choose cek1 and cek3, the message "You choose cek1 and cek3"

and so on. .. ..

I've been using code like this:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim i As Integer
        Dim ChName As String
        Dim chCek As String
        For Each ctl As Control In Me.Controls
            If ctl.Name.Contains("Chkbox") Then  'Name of checkboxes
                Dim chk As CheckBox = TryCast(ctl, CheckBox)
                If chk.Checked Then i = i + 1
                If i > 2 Then
                    i = i - 1
                    MessageBox.Show("you may only select 2 checkboxes", "Info", MessageBoxButtons.OK)
                    Exit Sub
                End If
                If i < 1 Then i = 0
                Debug.Print("Nama Checkbox : " & chk.Name & vbCrLf & "Status : " & chk.Checked.ToString)
                ChName = chk.Name  'Variable to hold the properties 'Name' of the checkbox control
                chCek = chk.Text   'Variable to hold the properties 'Text' of the checkbox control
            End If
        Next
        MsgBox("number of checkboxes selected are : " & i.ToString & vbCrLf & "checkbox that you select are : " & ChName & vbCrLf & "Status : " & chCek.ToString & "", "Information", vbOK)

    End Sub

but still can not.

i need your help, guys...

thank you.

An easier way to loop over specific controls is

For Each chk As CheckBox In Me.Controls.OfType(Of CheckBox)()

so your code then becomes

Dim numChecked As Integer = 0
Dim message As String = "You checked "

For Each chk As CheckBox In Me.Controls.OfType(Of CheckBox)()
    If chk.Checked Then
        numChecked += 1
        message &= chk.Text & " and "
    End If
Next

If numChecked > 2 Then
    MsgBox("you may only select 2 checkboxes")
Else
    message = message.Substring(0, message.Length - 5)
    MsgBox(message)
End If
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.