Find Control

  • Thread starter Thread starter Jim Heavey
  • Start date Start date
J

Jim Heavey

I am trying to figure out what the difference is between these 2
commands and which I should be using...what the difference is...

I placed this tag on my form...
<div id="fred" runat="server"></div>

I wrote these 2 statements to find the control....

HtmlGenericControl cntrl = (HtmlGenericControl) Page.Controls
[1].FindControl(CntrlName);

HtmlGenericControl cntrl2 = (HtmlGenericControl) Page.FindControl
(CntrlName);


Both apparently work and populate cntrl and cntrl2 with something.

I know (or believe) the first one looks at a particular "instance" of
controls, but I would have no idea as to what to set the index to for
him to begin his search. Does not seem to care if I put 1 or 0 as far
as the indexer goes. Why would this be?
 
the current page is a control in Controls collection, in your sample case
index 1, thats why the FindControl works the same. index )

-- bruce (sqlwork.com)
 
Hi Jim,

The first thing you need to understand is that the FindControl() method only
looks at the immediate children of a Control, not children nested inside
other Controls under a Control. The second thing is that most likely your
Control is inside your WebForm (the "form runat=server" Control in the
Page), which means that it is at least inside that Control, and not the Page
that contains the WebForm. If it is inside another Control in the WebForm,
you would have to locate it in THAT Control's Controls Collection.

If you know which Control in the Page is the immediate parent, it's a
relatively simple matter to find it. If you are unsure, you can always
create a recursive function that searches throuigh the entire Page's
hierarchy of Controls to find the one you're looking for.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
Back
Top