.Net coding can be frustrating, when you're trying and failing to do something simple. In this case, I was trying to enable or disable a RequiredFieldValidator based on some criteria.  I knew the ID of the controls I was trying to enable, but due to various templates and custom controls, a normal Page.FindControl() call didn't work - ASP.Net prepends a load of extra guff onto your original ID.

A hack that I've see used in cases like this is to hardcode the newly-nested ID, eg:

Page.FindControl("ctl00_MyRegion_ExtraRegion_mycontrolname")

Obviously this is not ideal, as if the page template changes in any way, our code will stop working.
The quick fix needed in my particular case was to use a better version of FindControl - one which recursed through every control on the page if need be.
Luckily, thanks to the wonders of Google and various useful bloggers, I was soon spoiled for choice for suitable functions.
The solution I chose to use was from:

http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx

...and it was further refined here: 

http://intrepidnoodle.com/articles/24.aspx

As an aside, I still don't understand why Microsoft make some things so needlessly complex. I much prefer the PHP way of doing things when it comes to form fields - they are all just readily accessible in an associative array.

Written by Celerity Design, on February 28, 2008
Tags:




Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
Security Code: