Options to using FindContro()

The thing I don’t like about FindControl() is the string parameter. If the ID has been changed the compiler won’t pickup the error. The error will only occur at runtime. It would be nice if we could get the reference using a method that the compiler would check at compile time? Any ideas/comments?


No, as the find control is way of finding a control at runtime. So the compiler has no way of knowing. If you want the compiler to catch it, you need to call if via its id.

This is why I tend towards the idea that 99% of the time you are using findcontrol, you are doing something wrong. What are you trying to do, there is probably a better way.

I agree with wwb on this one. The only time I ever use .FindControl is if its inside a repeater databound event or gridview. Or if I need to find a control on the master page. But barely ever using the later as I just think its bad practice most of the time.

^^^^Yup, and there are ways to avoid those problems in many cases, or at least limit the use of FindControl.

Give me an example of what you consider doing something wrong?

I use FindControl() for finding controls in any of the templated controls, such as FormView and GridView. I find the tradeoff of using FindControl() versus implementing ITemplate.InstantiateIn(…) a reasonable tradeoff. If there is a better way, I am all ears.

Thanks, Mike

I use FindControl() with templated controls too.

Programmatically adding controls to a page would be the only other option, correct?

How about an example of a poor use of FindControl()? I can’t imagine anyone using FindControl() when the reference is available in intellisense.

Thanks, Mike

Ok, so how do you reference a control in a Master page? Is there another way other than using FindControl()? Give an example of what you consider bad practice?

I place panels in the Master page for displaying error messages.

Thanks, Mike

Well, like we said. There are some cases where .FindControl() is perfectly acceptable. I do not consider using .FindControl() bad practice. I think its bad practice having controls on the master page that is set from child pages or controls. As it makes the page depended on a specific master page.

If you are using .FindControl() and its working well with dynamic controls, then leave it be. You could also loop through the controls, coz without seing any code, it is hard to say if there is a better option for what your doing without .FindControl()

For master pages, I use some base interfaces and classes as a container construct. Or, the page “bubbles” an error message out, and the master knows how to display it. See this blog post for an example with buttons, but can be applied to any server control.

What I try and do for repeated, databound controls is to use repeaters of UserControls, this keeps your FindControl calls to a minimum. After that I just deal with properties and methods on the UC.