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
If you're using MasterPages
and this control is in a page sitting in a ContentPlaceholder
, you cannot get the reference to the control via FindControl
directly, since the only control in the page's ControlCollection
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 and FindControl
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 a MasterPage
it is the ContentPlaceHolder
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:
Page.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1");
http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx
But why don't you simply reference your control directly? For example:
this.TextBox1.Text = "Hello World";
By the way, this is derived from my own answer on a similar question.
Put a place holder around the text box in the markup, like this:
<asp:PlaceHolder ID="MyPlaceHolder" runat="server>
<asp:TextBox ID="MyTextBox" runat="server" />
</asp:PlaceHolder>
Then you can fin the text box using:
TextBox formTextBox = MyPlaceHolder.FindControl("MyTextBox") as TextBox;
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