How to dynamically add <asp:> controls to a webpage?

J

Jim Bancroft

Hi everyone,

I've been working with ASP.Net for about a month, and in all the samples
I've seen the authors know ahead of time how many DropDownLists or Labels
they're going to need.

My problem is that I don't always know at design time how many (for
instance) DropDownLists I'll need. As an example, one of my old asp pages
queries a table and loops through the resulting recordset, adding one
DropDownList per entry and populating it with the values from another
recordset.

I'm not sure how best to do this sort of "dynamic control creation" in
asp.net and was wondering if anyone could post a bit of sample code or nudge
me in the right direction? Should I / must I do this sort of thing in the
aspx file or can it be done in the code-behind file too? I'm not sure.

Thanks for the help.

-Jim
 
C

CJ Taylor

OnPageLoad

Dim MyDropDown as DropDownList
Dim i as integer

For i = 0 to 10
MyDropDown = new DropDownList()

MyDropDown.id = "ddl" & i

me.controls.add(myDropDown)

Next

You can probably get the hang of it from there.

-Cj
 
J

Jim Bancroft

Thanks very much.....

I don't suppose if you know how to place these items after they're created?
Right now I'm getting a runtime error that says "Control 'ddl0' of type
'DropDownList' must be placed inside a form tag with runat=server"

-Jim
 
J

Jeff Evans

Jim Bancroft said:
Thanks very much.....
I don't suppose if you know how to place these items after they're
created? Right now I'm getting a runtime error that says "Control
'ddl0' of type 'DropDownList' must be placed inside a form tag with
runat=server" -Jim


You'll probably want to create a placeholder control in the designer for
your aspx page. Then you dynamically add controls to the Controls
collection of that placeholder.

Be warned that dynamic controls can be quite tricky, and although their
behavior is very predictable it can sometimes be very hard to track down
bugs, especially with postback/viewstate. I highly reccomend you read this
article, which despite dealing with Viewstate more than anything else is
nonetheless very helpful in understanding the page life cycle, which is
crucial to dynamic controls:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/viewstate.asp
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top