无法在此处输入“item here”类型的对象来输入“item here”

时间:2013-11-16 17:19:38

标签: vb.net runtime-error

当我做类似的事情时:

For Each item As HScrollBar In Me.Controls 'ERROR: Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.Windows.Forms.HScrollBar'.
item.Visible = False
Next

我收到错误,因为我对Windows窗体上的控件不是hscrollbar的项目。

1 个答案:

答案 0 :(得分:2)

是的,这不是正确的代码。 Me.Controls包含控件,而不仅仅是滚动条​​。修正:

    For Each item As Control In Me.Controls
        If TypeOf item Is HScrollBar Then
            '' etc..
        End If
    Next

或者更清洁的Linq版本:

    For Each item As HScrollBar In Me.Controls.OfType(Of HScrollBar)()
        '' etc..
    Next
相关问题