2016-12-12 8 views
0

次のコードはうまくいきます。各ループのためにSelectionStart Doesnt Work

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

c変数はControlを入力したのメンバーではありません。ベースControlタイプにはSelectionStartプロパティがありません。これをTextBoxにキャストするには、何らかの仕組みが必要です。

は、私はまた、より少ない全体的なコードで、その結果、if()条件を処理するOfType()方法、使用することをお勧めします:

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

ありがとうございました。 – Kramer