atrljoe
atrljoe

Reputation: 8151

FindControl in ASCX UserControl

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>

Upvotes: 0

Views: 5786

Answers (3)

JeffK
JeffK

Reputation: 3039

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... />

Upvotes: 0

Marcote
Marcote

Reputation: 3105

First check that contactsearch control is there in the control tree hierarchy. you can do this by simply exploring the Controls property of the control. If it's there, you need a recursive control search in order to find it.

Edit: Beaten by Antonio :P

Upvotes: 0

Antonio Bakula
Antonio Bakula

Reputation: 20693

FindControl searches only first childs, it doesn't go recursive into control tree, use something like this:

http://stevesmithblog.com/blog/recursive-findcontrol/

or this

http://ra-ajax.org/jquery-ish-selector-for-webcontrols

Upvotes: 1

Related Questions