lundi 31 juillet 2023

How to validate an user selection of multiple checkboxes on VB.net using a button?

everyone!

I'm learning VB.net language and I'm creating a simple app, which the user can select up to 5 numbers using checkboxes, and the button on windows form app will check if the user has marked up to 5 numbers. Otherwise, a dialog message will appear returning that user can only check up to 5 numbers, and the exceded choice is unchecked, keeping the 5 options checked. On some tests, I could do that setting the CheckBox1.CheckBoxChanged with the following code:

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged

Dim check As CheckBox = TryCast(sender, Object)
If check.Checked Then
    counter += 1
Else
    counter -= 1
End If
If counter > 5 Then
    MessageBox.Show("You can only pick up to 5 numbers!")
    check.Checked = False
End If

End Sub

On this way the program has worked perfectly. But it's failed when I've tried to implement on the button1.click. I even tried some another methods, like this:

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

For Each check As CheckBox In Me.grpMega.Controls.OfType(Of CheckBox)()
    If check.Checked Then
        counter += 1
    Else
        counter -= 1
    End If
    If counter > 5 Then
        MessageBox.Show("You can only pick up to 5 numbers!")
        check.Checked = False
    End If
Next

End Sub

I've beend making some searches over the internet to find up a solution, but with no success. If anybody could help me, I'll be so grateful. Thanks so much for your attention. Any help is very welcome.




Aucun commentaire:

Enregistrer un commentaire