2013-01-12 458 views
0

顯示錯誤無法轉換類型「system.windows.forms.combobox」的對象鍵入「system.windows.form.DateTimePicker」在我的代碼...對象鑄造錯誤

Private Sub UncheckMyControlsdtp() 
    Dim dtp As DateTimePicker 
    Try 
     For Each dtp In EMPGBDATA.Controls 
      If dtp.CalendarMonthBackground = Color.Red Then 
       dtp.CalendarMonthBackground = Color.White 
      End If 
     Next 
    Catch e As Exception 
     MsgBox(e.Message) 
    End Try 
End Sub 

朋友檢查我代碼並給予解決方案...

+0

ctrl是什麼類型? – Thanzeem

回答

1

您應該檢查你是從EMPGBDATA.Controls枚舉控件DateTimePicker類型:

Private Sub UncheckMyControlsdtp() 
    Try 
     For Each ctrl In EMPGBDATA.Controls 
      If TypeOf ctrl Is DateTimePicker Then 
       Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker) 
       If dtp.CalendarMonthBackground = Color.Red Then 
        dtp.CalendarMonthBackground = Color.White 
       End If 
      End If 
     Next 
    Catch e As Exception 
     MsgBox(e.Message) 
    End Try 
End Sub 
+0

ctrl是什麼類型? – Thanzeem

+0

它檢查循環中當前控件的類型是否是DateTimePicker,因此它不會嘗試在不是DateTimePicker控件的某些東西上運行代碼。 –

+0

@Thanzeem:ctrl的類型是'Control':'For Each ctrl As Control In EMPGBDATA.Controls' – xfx

1

的問題是,你iterati ng EMPGBDATA.Controls中的所有控件,其中一些不是DateTimePicker的實例。您將不得不手動檢查For Each循環,以確保實例是正確的類型。像這樣:

Private Sub UncheckMyControlsdtp() 
    For Each ctl As Control In EMPGBDATA.Controls 
     If TypeOf ctl Is DateTimePicker Then 
      Dim dtp As DateTimePicker = DirectCast(ctl, DateTimePicker) 

      If dtp.CalendarMonthBackground = Color.Red Then 
       dtp.CalendarMonthBackground = Color.White 
      End If 
     End If 
    Next 
End Sub