如何动态更改复选框检查状态

时间:2015-09-23 14:59:36

标签: .net vb.net visual-studio checkbox controls

我正在运行Visual Studio 2015的社区版。

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

我在下面显示了用于创建复选框的代码,并在底部显示了我试图用来更改值的代码。我很感激任何建议。

        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

1 个答案:

答案 0 :(得分:1)

这一行试图在没有该属性的通用控制对象上设置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
相关问题