The correct method to dynamically create controls in web form

Source: Internet
Author: User

Many ASP. NET
For beginners
The problem with the dynamic creation of controls in form is that the common problem is that the dynamically created controls cannot have the same effect as the controls dragged to the screen, for example, viewstate cannot be loaded.
And dynamic control event processing.

The following example shows how
Create a textbox dynamically on Form
And button
Control, and process the button
Click
Event.

1 protected sub page_init () sub page_init (byval sender as object, byval e as system. eventargs) handles me. init
2 dim otextbox as new Textbox ()
3 dim obutton as new button ()
4
5 otextbox. ID = "mytextbox"
6. The initial value of otextbox. Text = "AAA" 'textbox is AAA.
7 me. Form. Controls. Add (otextbox)
8
9 obutton. ID = "mybutton"
10 obutton. Text = "button"
11 me. Form. Controls. Add (obutton)
12
13 'direct the button's click event to the button_click Function
14 addhandler obutton. Click, addressof button_click
15 end sub
16
17
18 'button's Click Event-Oriented Function
19 protected sub button_click () sub button_click (byval sender as object, byval e as system. eventargs)
20 dim otextbox as textbox = nothing
21 otextbox = ctype (Me. findcontrol ("mytextbox"), textbox)
22 if otextbox isnot nothing then
23 otextbox. Text = "BBB"
24 end if
25 end sub

Why do we need to dynamically create controls in the init event, instead of Load
What about the event? The main reason is init.
Event in loadviewstate
Previously occurred, while load
The event is in loadviewstate
Later. You want to go to loadviewstate
The control is ready before the viewstate
Load and update the property value of the control.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.