对于每个循环SelectionStart不起作用

时间:2016-12-12 00:31:19

标签: vb.net

以下代码效果很好;

    For Each c As Control In TabPage1.Controls
        If Not TypeOf c Is Label Then
            c.Enabled = False
        End If
    Next

以下代码效果很好;

    TextBox1.SelectionStart = 0

以下代码无效;

    For Each c As Control In TabPage1.Controls
        If TypeOf c Is TextBox Then
            c.SelectionStart = 0
        End If
    Next

这是错误消息;

' SelectionStart'不是System.Windows.Forms.Control'

的成员

1 个答案:

答案 0 :(得分:1)

c变量的类型为Control。基本Control类型没有SelectionStart属性。您需要一些机制将其强制转换为TextBox

我建议使用OfType()方法,该方法也会处理if()条件,从而减少整体代码:

For Each c As TextBox In TabPage1.Controls.OfType(Of TextBox)()
    c.SelectionStart = 0
Next c

但你也可以选择更传统的DirectCast()

For Each c As Control In TabPage1.Controls
    If TypeOf c Is TextBox Then
        Dim t As TextBox = DirectCast(c, TextBox)
        t.SelectionStart = 0
    End If
Next

TryCast()选项:

For Each c As Control In TabPage1.Controls
    Dim t As TextBox = TryCast(c, TextBox)
    If t IsNot Nothing Then
        t.SelectionStart = 0
    End If
Next