Xanmashi
Xanmashi

Reputation: 167

Visual Basic - Checkbox states

Okay so what I want to do is whilst one Checkbox is checked and in this instance 'Addition' will be checked > whilst it is checked how would I make a pop-up saying "You cannot select more than two values at once" or something so they can't check two boxes and crash the program. Here is my code:

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

    Dim Addition As String
    Dim Subtraction As String
    Dim Multiplication As String

    Multiplication = CheckBox3.CheckState
    Subtraction = CheckBox2.CheckState
    Addition = CheckBox1.CheckState

    If Addition = CheckState.Checked Then
        'label icon of the current calculation sign 
        neum.Text = "+"
        'label icon of the current calculation sign
        Me.CheckBox2.CheckState = CheckState.Unchecked
        Me.CheckBox3.CheckState = CheckState.Unchecked
    End If

    If Addition = CheckState.Unchecked Then
        neum.Text = " "
    End If
End Sub

Upvotes: 0

Views: 1046

Answers (1)

Josh
Josh

Reputation: 1093

The code you've written should work if you declare Addition, Subtraction and Multiplication as booleans instead of strings.

Dim Addition, Subtraction, Multiplication As Boolean

Alternatively, since you only reference one of the variables one time, you could get rid of them completely. (With the approach you're taking, you need similar handlers for CheckBox2.CheckedChanged and CheckBox2.CheckedChanged, but there is no reason for each handler to examine all the CheckBoxes; only the one it is handling.

If CheckState.Checked Then
    neum.Text = "+"
    Me.CheckBox2.CheckState = CheckState.Unchecked
    Me.CheckBox3.CheckState = CheckState.Unchecked
Else
    neum.Text = " "
End If

As commented above, Radio Buttons are the preferred control for giving a user a list of choices of which they may select only one. Here's a code suggestion for that approach:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'You don't have to do this with code
    'You can manually set the "Tag" property in the designer instead
    RadioButton1.Tag = "+"
    RadioButton2.Tag = "-"
    RadioButton3.Tag = "*"
End Sub

Private Sub RadioButtonChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged, RadioButton3.CheckedChanged
    neum.Text = Sender.Tag
End Sub

Upvotes: 1

Related Questions