I have a textbox on a page but when i use
TextBox formTextBox = Page.FindControl(textBox) as TextBox;
it comes back null
. Is there a way around this? I know the control is on the page but i cant find it.
Thanks
I have a textbox on a page but when i use
TextBox formTextBox = Page.FindControl(textBox) as TextBox;
it comes back null
. Is there a way around this? I know the control is on the page but i cant find it.
Thanks
One of two things is happening... either the control is not being found (this is the most likely) or it is not returning a TextBox
object.
The thing to remember about FindControl
is that it is NOT recursive... it will only look at the top-level child controls. So, if your text box is nested inside another control, it will not be found. you can read the MSDN docs here.
You may want to make your own version of FindControl that will search inside nested controls--implementing such a method is trivial and can be found easily using your google-foo
If you're using
MasterPages
and this control is in a page sitting in aContentPlaceholder
, you cannot get the reference to the control viaFindControl
directly, since the only control in the page'sControlCollection
is the MasterPage itself. That makes sense. You cannot guarantee an ID to be unique when the control is on the top level of a page with MasterPage, because other ContentPages might as well have a control with this ID andFindControl
could today return another control than tomorrow.If you look at the
NamingContainer
of the Control you want to find, you see that in case of aMasterPage
it is theContentPlaceHolder
and in case of a "normal" Page it is the Page itself.So you need to get a reference to the MasterPage's ContentPlaceholder first before you could find the control via FindControl:
http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx
But why don't you simply reference your control directly? For example:
By the way, this is derived from my own answer on a similar question.