Alex Rivera | Logout

ASP.Net FindControl is not working - How come?

Asked 2009-04-28T20:21:20.687
32

I have used FindControl in the past, prior to .NET 2.0/3.0. It seems like now, for some reason, the ID's of my controls get a funky named assigned. For example I assigned an id "cbSelect" to a checkbox, but FindControl does not find it. When I view the HTML it was assigned ctl00_bodyPlaceHolder_ctl02_cbSelect.

I have not found one example of FindControl that mentions that. In fact everyone seems to just use find control like normal.

So, am I doing something wrong? Did .Net change? Can anyone shed some light onto this for me, it is really frustrating!

Edit
Report

1 Answer

7

When searching for a control in a control collection, always use the id you assigned the control, not the one you see in the source post render. If FindControl() does not find the control you know exists, there is a good chance that you are not searching in the right branch of the control hierarchy. A recursive function has been successful for me.

Here is my example of what I use for VB.NET 3.5:

Function FindControlRecursive(ByVal ctrl As Control, ByVal id As String) As Control
    Dim c As Control = Nothing

    If ctrl.ID = id Then
        c = ctrl
    Else
        For Each childCtrl In ctrl.Controls
            Dim resCtrl As Control = FindControlRecursive(childCtrl, id)
            If resCtrl IsNot Nothing Then c = resCtrl
        Next
    End If

    Return c
End Function

Here is an example of how I would topically implement this function in my base page class:

Dim form HtmlForm = CType(FindControlRecursive(Me, "Form"), HtmlForm)
answered 2010-03-02T20:57:02.197

Your Answer