I am trying to find a control a DIV that I have set to runat server in my ascx file, but when I debug it, I get the value of findcontrol is null so its not finding it, what am I doing wrong?
This being called from my ASPX page:
HtmlGenericControl div = (HtmlGenericControl)FindControl("search");
div.Visible = false;
My ASCX Code:
<div class="contactsearch" id="search" runat="server" visible='true'>
//mycontent
</div>
You can search using a recursive algorithm, as discussed in Markust and Antonio's answers, and it will work in this instance. However, it has a few problems. For example, it won't work if you have two instances of the usercontrol on your page.
However, the bigger problem is that you're breaking the encapsulation that a usercontrol provides. The containing page should not know that a usercontrol contains, say, a Textbox named "txtSearchCriteria," or a button named "btnSearch." (Or a <div>
named "search.") The containing page should only work with the usercontrol using the interface that the usercontrol exposes publicly.
I recommend that you create a property (or set of properties) in the usercontrol to allow consumers to intreact with the control in ways that you expect them to. For example:
Public Boolean SearchControlsVisible
{
get { return search.Visible; }
set { search.Visible = value; }
}
The property's code can access the "search"<div>
without ambiguity, even if you have multiple instances of the usercontrol on the page. This approach also gives you the ability to set those properties in the ASPX markup when you place the control on the page:
<my:ContactSearchPanel ID="contactSearch runat="server"
SearchControlsVisible="false"
...etc... />
It's not in your question, but you'll need to respond to events that occur in the usercontrol as well. For instructions on raising events from a usercontrol, see this page: http://msdn.microsoft.com/en-us/library/wkzf914z(v=vs.71).aspx
Once you've created and exposed an event, you can attach a handler in the markup like this:
<my:ContactSearchPanel ID="contactSearch runat="server"
SearchControlsVisible="false"
OnSearchClicked="SearchPanel_SearchClicked"
...etc... />