Search code examples
c#.netasp.netfindcontrol

ASP.Net FindControl is not working - How come?


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!


Solution

  • You are probably using a MasterPage or user controls (ascx) and this is the reason the for client ids change. Imagine you have a control in the master page with the same id as one in the page. This would result in clashes. The id changes ensures all ClientID properties are unique on a page.

    FindControl needs some special attention when working with MasterPages. Have a look at ASP.NET 2.0 MasterPages and FindControl(). The FindControl works inside a naming container. The MastePage and the page are different naming containers.