Finding a dynamically added control - Quite Urgent :-(

S

Simon Harvey

Hi All.

In one of my user controls I add a textbox to a placeholder sitting on the
user control.

txtUsername = new TextBox();
txtUsername.ID = "txtUsername";
phUsernamePlaceholder.Controls.Add(txtUsername);

Then in an event handler for the pages save changes button I try to find the
control via:

TextBox = ((Textbox)this.FindControl("txtUsername")).Text;

Unfortunately, this isn't working - it can't find the control.

Can anyone tell me where my control has gone?

Thanks all!

Simon
 
T

Teemu Keiski

Hi,

you would need to look inside the naming container of the TextBox, that
would be the user control e.g run FindControl against the user control.

Another way could be exposing the TextBox outside the user control as an
property (create a member that references the TextBox, when you instantiate
it and then create a property which accesses this member).
 
K

Kevin Spencer

The FindControl() method is part of the System.Web.UI.Control base class,
and is therefore common to all System.Web.UI.Controls. It will find a
Control by the given ID in the Controls Collection of the Control for which
it is called. It doesn't work recursively. That is, it only searches the
Controls Collection of the Control for which it is called; it doesn't search
the Controls Collection of every child Control of that Control.

According to your message, you most likely have a WebForm, which is an ASPX
page with a runat=server form on it. Inside that form, you have a User
Control. Inside that, you have a PlaceHolder. Inside the PlaceHolder, you
have a textbox. Let's diagram the hierarchy of Controls:

Page
Form
UserControl
PlaceHolder
TextBox

When you call this.FindControl() in the context of a Page class, you are
searching the Controls Collection of the Page. Note that, according to our
hierarchy diagram, the TextBox is NOT a member of the Page's Controls
Collection. It is a member of the PlaceHolder's Controls Collection. you
would have to call the FindControl() method of your PlaceHolder to get to
the TextBox.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top