Search code examples
vb.netbuttoncheckboxappearance

Changed checked state on checkbox with button appearance in VB.NET


As stated in my summary, I am currently working on a Virtual OS in VB.Net. I am currently working on the session as I am done with the login stuff.

I am having trouble with a checkbox with button appearance. I want to set the CheckState to Checked if I click on the button with the Click() event like this:

    Private Sub btnApps_Click(Byval sender As Object, Byval e As EventArgs) Handles btnApps.Click()
       If btnApps.CheckState = CheckState.Checked Then
          btnApps.CheckState = CheckState.Unchecked
       Else
          btnApps.CheckState = CheckState.Checked
       End If
    End Sub

I also tried the Checked property.

This code is not working at all, if I put the whole If-End If section in the CheckedChanged event I get a StackOverflowException. What am I doing wrong?

The CheckBox is a custom control b.t.w.


Solution

  • If you'd like to prevent your Checkbox from automatically changing state and change the appearance with your own Click event, you can turn AutoCheck to false.

    https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.autocheck(v=vs.110).aspx

    Information found thanks to this question: How to cancel RadioButton or CheckBox checked change

    Public Class Form1
    Private WithEvents btnApps As New clsChk
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        btnApps.AutoCheck = False
        Me.Controls.Add(btnApps)
    End Sub
    
    Private Sub btnApps_Click(sender As Object, e As EventArgs) Handles btnApps.Click
        Debug.WriteLine(btnApps.CheckState)
        If btnApps.CheckState = CheckState.Checked Then
            btnApps.CheckState = CheckState.Unchecked
        Else
            btnApps.CheckState = CheckState.Checked
        End If
    End Sub
    End Class