Thursday, August 16, 2007

FindControl and UniqueID

The FindControl method is not recursive. Should have done that Google query before I spent 3 hours debugging.

Imagine you've gotten a page that adds user controls very late in the page lifecycle - after Init, in any case. Like any good control developer, you're definitely going to recreate the control tree after postback, but you have some additional requirements. In addition to adding the control to the tree, you need to keep track of certain types of controls, and re-apply some properties to them. Like, a "collapsed" property, for instance.

So, you throw some control ID's into a StateBag (I really like that class name) to retrieve later, to apply the properties to each control. You have the ID, and you have the control type - should be easy to find the controls on each page, and then apply properties, right?

Wrong. Not if you don't know where in the tree it is. Page.FindControl(controlID) doesn't work if it's deep in the tree. However, using our handy-dandy Reflector, we can see that FindControl uses ID and UniqueID, which:

Gets the unique, hierarchically qualified identifier for the server control.

Ahhh...just what I need. The ID and where it is in the tree - all without having to to implement FindControlRecursive (for now).

4 comments:

Anonymous said...

Could you provide a code sample then?

Nic Webb said...

I'm not sure what kind of code sample you're wanting. I just called FindControl with the UniqueID (which was saved) instead of the ID.

E. Zele said...

Thank you for sharing! The MSDN Library doesn't mention this at all. I was looking for this to get the reference to the control which is in the __EVENTTARGET hidden field of the page, from within a WebControl. I had to use Page.FindControl though.

dotNetFollower said...

Nice post! My own FindControlRecursive helped me out many times. Especially, when I deal with MasterPages. For example, one of such usage is shown in my post here – http://dotnetfollower.com/wordpress/2010/12/sharepoint-add-onchange-attribute-to-dropdownchoicefield/.
Thank you!