2016-12-12 55 views
0

以下代碼很好用;For Each Loop 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

我建議使用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 
+0

非常感謝。 – Kramer