2016-12-12 4 views
0

folgenden Code funktioniert gut;für jede Schleife Selection arbeitet nicht

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

Der folgende Code funktioniert großartig;

TextBox1.SelectionStart = 0 

Der folgende Code funktioniert nicht;

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

Dies ist die Fehlermeldung;

'Selection' ist kein Mitglied von 'System.Windows.Forms.Control'

Antwort

1

c Die Variable hat Control eingeben. Die Basis Control Typ hat keine SelectionStart Eigenschaft. Sie benötigen einen Mechanismus, um dies zu einem TextBox zu werfen.

Ich empfehle die OfType() Methode, die auch die if() bedingte behandelt, in insgesamt weniger Code resultierende:

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

Aber auch für die konventionellere DirectCast() gehen könnte:

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 

Oder die TryCast() Option:

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 
+0

Vielen Dank. – Kramer