Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Refering to Dynamically Added Controls

Status
Not open for further replies.

RobHudson

Programmer
Apr 30, 2001
172
GB
Hi!

I am adding controls to an ASP.NET page at runtime. Because of the nature of the task there could be any number of new controls added.

Does anybody know how I refer to these controls once a button has been clicked to submit the form? A method of looping through them would be ace!

The new cotrols live in a panel (not created at runtime). I have tried doing a FindControl on the panel, but am having no joy :(

Ideas would be great!

Cheers
Rob
 
If the controls are added dynamically, you have to loop through them after they have been created and exist on the form. They will be recreated whenever you load the page, but as (I'm assuming here) your page runs and displays the controls even after a PosBack you probably know this
Try the below...

// Loop through Controls on Panel
for each (Control c in panel.Controls)
{
// Check control types and action for each type
// If it's a TextBox...
if(c is TextBox)
{
// Cast control to Web.TextBox control
TextBox t = (TextBox) c;
// and do whatever you want to it...
}
// If it's a Button...
if (c is Button)
{
// Cast control to Web.Button control
Button b = (Button) c;
// and do whatever you want to it...
}
}

Rhys
Thought out... Maybe,
Opinionated... Probably
But it is only an opinion!
 
Thanks for that Rhys ;)

I think I may have hit another issue here as the controls don't display once the page is posted back. I am now guessing that, that is the reason why I can not refer to them???

If that's the case, how do I ensure that the new controls are dislpayed on postback?

To help, here is what happens...
+ A list is clicked and submits the form.
+ Controls are created/displayed depending on what has been clicked in the list.
+ Click a button that submits and should[!] read the controls and then take the use else where.

thanks for any help
Cheers
rob
 
OK.

Page_Load occurs before the Buttons click event, so you need to rebuild dynamic controls on the page before looping through them in your buttons click event. I would suggest that in the Buttons click event, you need to run the same code that populates the controls on the page, (I.E., the code that runs when selecting the item from the list), before looping through the controls on the Panel.

OK?


Rhys
Thought out... Maybe,
Opinionated... Probably
But it is only an opinion!
 
Thanks buddy :)

Sounds like the way forward!!

Cheers
rob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top