views:

23

answers:

1

Hi All,

I have created a couple of simple functions in VB.NET that simply return a control of a certain type that I already know, such as HtmlInputHidden, Label, etc. That means that each of the functions is created only for that special purpose.

What I'd like to do is combine all those functions into one function using generics. The common things shared by each of the functions is a control Id and a control type.

What I have got so far is:

   Public Function GetControl(Of T)(ByVal ctrlId As String) As T
        Dim ctrl As Control = Me.FindControl(ctrlId)

        If (Not ctrl Is Nothing) Then
            GetControl = CType(ctrl, T)
        Else
            GetControl = Nothing
        End If
    End Function

But the line " GetControl = CType(ctrl, T)" is giving me a compile error:

   Value of type 'System.Web.UI.Control' cannot be converted to 'T'

This is in .NET Framework 2.0.

Any insight is highly appreciated.

John

+2  A: 

If you change your function to this, it will work.

Public Function GetControl(Of T)(ByVal ctrlId As String) As T
    Dim ctrl As Object = Me.FindControl(ctrlId)

    If (Not ctrl Is Nothing) Then
        return  CType(ctrl, T)
    Else
        return  Nothing
    End If
End Function

This is due to the fact that the type needs to be in a way that it can convert, as if you convert to a control, it would be upcasting to the concrete type.

Now, be sure to keep in mind that you could throw exceptions here if your send the id of the wrong type, etc.

Mitchel Sellers
That is it! Thank you so much for the prompt reply.
John
No problem! Glad i could help
Mitchel Sellers
Could use TypeOf and DirectCast to avoid any errors.
Saif Khan
Thanks Saif for the reminder.I wanted to post the update here but not sure how.
John