about FindControl ---> to find the control added by program

E

Edward

hi, everyone,
my Page_Load fill tblProducts with some TextBox.

<form runat="server">
<asp:Table id="tblProducts" runat="server"></asp:Table>
<hr>
<asp:Button id="Button1" onclick="Button1_Click" runat="server"
Text="Button"></asp:Button>
<hr>
<hr>
<asp:TextBox id="test" runat="server"/>

</form>

the method is :

TextBox getTextBox() {
TextBox txt = new TextBox();
txt.ID = "txtNum" + Convert.ToString(TextBoxCnt);
TextBoxCnt ++;

return txt;
}


when I use :
TextBox txt = (TextBox)Page.FindControl("txtNum" + Convert.ToString(i));

in the script of Button_Click, I cannot find the control. but in
Page_Load , I can get it.

And in Button_Click, TextBox "test" can be find.

How can I find the program-added controls in Button_Click?

thanks.
 
S

S. Justin Gengo

Edward,

My guess is that you may be adding the controls only on page load and not
post back.

For dynamically added controls to be accessible on post back they must be
added to the page again.

I have an example of this (in VB.Net, but you should get the idea) on my web
site, www.aboutfortunate.com, just go to the code library (link on the top
right of page) and search for "Dynamically add text boxes".

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
E

Edward

Thanks, Justin.

You are right. I put the code outside "postback=false".

although I got the result, but I was confused about the mechanism, How can
the textbox's value be refreshed when the second-Page_load runs ?

Thanks from heart.
 
S

S. Justin Gengo

Edward,

Each control's properties are gathered upon page load. .NET runs through
each control on page load and fills it's properties from the post, but it
only loops through controls that exist. So if a control isn't recreated the
control is never matched up with the post from the client.

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top