Ross from Brooklin
Ross from Brooklin

Reputation: 303

How do I dynamically change check box check state

I am running the Community version of Visual Studio 2015.

I am trying to dynamically change the CheckState property of a dynamically created check box using Me.Controls...CheckState = CheckState.Unchecked, but I am getting a compile time error saying that CheckState isn't a member of Controls.

I show below both the code I used to create the check box and, at the bottom, the code I`m trying to use to change the value. I'd appreciate any suggestions.

        cbPDF.Location = New Point(710, tvposition)
    cbPDF.Size = New Size(80, 20)
    cbPDF.Name = "cbPDF" + panposition.ToString
    cbPDF.Text = "PDF Conv"
    cbPDF.CheckState = CheckState.Unchecked
    Controls.Add(cbPDF)
    AddHandler cbPDF.CheckedChanged, AddressOf Me.CommonCheck
    arrTextVals(10, panposition) = "cbPDF" + panposition.ToString
    arrTextVals(11, panposition) = "unchecked"

    If arrTextVals(11, bottomLine) = "unchecked" Then
        Me.Controls(arrTextVals(10, bottomLine)).CheckState = CheckState.Unchecked
    Else
        Me.Controls(arrTextVals(10, bottomLine)).CheckState = CheckState.Checked
    End If

Upvotes: 1

Views: 2973

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27342

This line is trying to set the CheckState on a generic control object which doesn't have that property.

Me.Controls(arrTextVals(10, bottomLine)).CheckState = CheckState.Unchecked

You need to cast it to a checkbox in order to set this property (you need to be sure that it actually is a checkbox or this will produce a runtime error):

DirectCast(Me.Controls(arrTextVals(10, bottomLine)), CheckBox).CheckState = CheckState.Unchecked

or long-hand for easier reading:

Dim ctl As Control = Me.Controls(arrTextVals(10, bottomLine))
Dim chk As CheckBox = DirectCast(ctl, CheckBox)
chk.CheckState = CheckState.Unchecked

Upvotes: 1

Related Questions