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

朋友检查我的代码并给出解决方案...

4

2 回答 2

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
于 2013-01-12T08:38:54.653 回答
1

问题是您正在迭代 中的所有控件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
于 2013-01-12T08:39:01.697 回答