如何动态更改复选框选中状态

How do I dynamically change check box check state

我是 运行 Visual Studio 2015 的社区版本。

我正在尝试使用 Me.Controls...CheckState = CheckState.Unchecked 动态更改动态创建的复选框的 CheckState 属性,但我收到编译时错误,指出 CheckState 不是 Controls 的成员。

我在下面显示了我用来创建复选框的代码,以及在底部我试图用来更改值的代码。如果有任何建议,我将不胜感激。

        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

此行试图在没有 属性 的通用控件对象上设置 CheckState。

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

您需要将其转换为复选框才能设置此 属性(您需要确保它实际上是一个复选框,否则会产生运行时错误):

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

或为了便于阅读而使用长手写法:

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