tags:

views:

77

answers:

1

Hi,

I get a compile error Type "ctltype" is not defined with this code.

This is .NET 1.1 legacy code so not good I know.

Anyone know why??

Public Function GetControlText(ByVal ctls As Control, ByVal ctlname As String, ByVal ctltype As Type) As String

        Dim ctl As Control
        Dim res As String


        ctl = ctls.FindControl(ctlname)
        If ctl Is Nothing Then
            Return ""
        End If

        res = CType(ctl, ctltype).Text

        If res Is Nothing Then
            Return ""
        Else
            Return res
        End If

    End Function
+2  A: 

The second operand for CType has to be a type name - not a variable which is of type Type. In other words, the type has to be known at compile time.

In this case, all you want is the Text property - and you can get this with reflection:

Public Function GetControlText(ByVal ctls As Control, ByVal ctlname As String, _
                               ByVal ctltype As Type) As String

    Dim ctl As Control = ctls.FindControl(ctlname)
    If ctl Is Nothing Then
        Return ""
    End If

    Dim propInfo As PropertyInfo = ctl.GetType().GetProperty("Text")
    If propInfo Is Nothing Then
        Return ""
    End If

    Dim res As String = propInfo.GetValue(propInfo, Nothing)
    If res Is Nothing Then
        Return ""
    End If
    Return res

End Function
Jon Skeet