Why it doesn't work?

U

Ufit

Dim img As New ImageButton
Page.Controls.Add(img)

It works with Image but ImageButton gives this error:
Control '1' of type 'ImageButton' must be placed inside a form tag with runat=server.

What's wrong???


Thanks

Ufi
 
C

CaffieneRush

ASP.NET follows the single form model therefore your imagebutton would
need to be added to a form which in turn is added to a page.
Normally the form is statically declared on a page (normally called
"form1") and the dynamically created controls would be added to the
statically declared form.

'Assume a form of ID "form1" is already statically decalred on a page.
Dim img As New ImageButton
form1.Controls.Add(img)
 
U

Ufit

Ok I got it but still when I add controls to form and f.ex. click on some button
my controls (UserControl) get destroyed. Why is that?
form1 is getting destroyed and reloaded as a new instance
It looks like it's not static so how to make it static?
Thanks

ufi
 
C

CaffieneRush

Yes, all controls gets destroyed after every response because of the
stateless nature of http.

The trick is to recreate it again on the next request. If you've
declaratively added your controls to the page then the ASP.NET
framework would automatically recreate your controls on each postback
and make it look like the controls were never destroyed.
Else if you are programmatically adding your controls then you have to
programmatically add the controls back on each postback.

To handle an event (eg.click) from a dynamically created control, you
need to first recreate the control (such as during page_load) otherwise
the event handler would never be called.

Andy
 

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,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top