The status of dynamically created controls cannot be saved in the code.

Source: Internet
Author: User

I found some information on the Internet and understood it. This is an article I think is helpful:

Original article: http://blog.csdn.net/keleloveni/archive/2007/03/15/1530300.aspx

Citation:

Today, I accidentally saw an article talking about related problems and finally solved something I didn't quite understand.

The first stage in the page lifecycle is instantiation. In this stage, automatically generated classes construct control hierarchies based on static controls defined in the HTML section of the page. When constructing a control hierarchy, the values specified in the declarative syntax are assigned to the attributes of each added control. After instantiation, It is the initialization phase. In this phase, the hierarchical structure of the static control has been constructed, but the view status has not been re-loaded (assuming that the page request is sent back ). If a page request is sent back, it is the loading view status stage after initialization. In this phase, the page filters the view status data found in the hidden viewstate form field. If necessary, each control in the control hierarchy updates its status.

If the page request is a send-back request, the view status is loaded and the data is returned. This phase checks the sent form field values and updates the properties of the corresponding control accordingly. For example, the post mechanism (indicating the name of the Textbox Control and the value entered by the user) is used to send the text entered by the user in the textbox web control. The page obtains these values, locates the appropriate textbox in the control hierarchy, and assigns the received value to its text attribute.

The next phase is the loading phase, which occurs when the page_load event handler is triggered. There are more stages after the loading phase, such as triggering a send-back event, saving the view status, and rendering Web pages.

The dynamic control needs to be added before loading the view status and re-loading the returned data, because we want to correctly add any view status or re-sending value specific to the dynamic control. With these restrictions in mind, the normal time for adding a dynamic control is in the initialization phase, because it occurs before the loading view status phase and the loading and re-sending data phase.

However, in the initialization phase, the view status and the returned data have not been restored, therefore, it is not recommended to access or set the control attributes that may be stored in the view State or modified by the return value (whether it is a dynamic or static control ), these values will be overwritten by the view status and return value in the subsequent stages of the lifecycle. When processing dynamic controls, I use the following mode:

In the initialization phase, I add a dynamic control to the control hierarchy and set the ID attribute.

In the loading phase, I assign any required initial values to the dynamic control in the if not page. ispostback Condition Statement.

Original article: http://blog.csdn.net/high_mount/archive/2007/03/18/1532481.aspx

Citation:

Introduction
Understanding the page lifecycle is very important for the development of Asp.net applications. Many. Net beginners have encountered problems such as Value Loss and status loss after sending back when handling dynamic loading controls. HTTP protocol is stateless, which is a natural problem between web programs and Windows programs. To learn about Asp.net, the lifecycle of page is one of the most important foundations. What is the sequence of events, especially when the parent board page is added to Asp.net 2.0, it becomes more complex, the purpose of this article is to explain the order and purpose of each event so that you can understand what these events are.

Background
In the Asp.net application, the user always requests. one of the things that interest us on the ASPX page is when users access one. what did the Web server of the application do on the ASPX page? Understanding the order of events will help us to do what we want in the right event, and eliminate some of our obfuscation, for example, you can blame the Stateless web application for some problems.

Basic: new compilation model and partial Classification)
Each web form in Asp.net inherits directly or indirectly from the system. Web. UI. Page class. A Web from consists of two parts: a code file (webform. aspx. CS), which includes some page-related events and methods, and the aspx file, which includes HTML control declarations (in the Web Application of Visual Studio 2005, we also have a webform. aspx. designer. CS design class)

In Asp.net 2.0, we do not need to define control variables or write some event delegation in the code file. All of this is due to the partial classification. In Asp.net 1.x, these codes are automatically generated in initializecomponent. However, in version 2.0, runtime creates a partial category, which contains all information on the ASPX page. This makes the code file very clear and easy to manage.

This will eliminate the change in the name of the code file and ASPX page in vs2003 (if we want to change the ID of any control, we have to change the ASPX page and code file ). The events of all controls in vs2005 are defined on the ASPX page. Therefore, the event Delegate and control variables in the code file will be cleared, which is easier than the previous vs2003.


Page Lifecycle
Understanding every request in the lifecycle of a page is very important. The loss of value or status may be caused by insufficient understanding of the lifecycle of the page. Of course, if you want to retain the status in Asp.net, you can use applications, sessions, cache, or cookies.

Note: The view status in Asp.net 2.0 consists of the control status and view status. For more information, see this article.
Http://msdn2.microsoft.com/en-us/library/1whwt1k7 (vs.80). aspx

Next we will introduce them in detail according to the trigger sequence of each event in the code file of the web program.

Note: All events except Init () and unload () are fired from the outermost to the innermost. For example, the init event of a user control is triggered before the page_init () event of its parent page class ).

1. preinit ()
In this page-level event, all controls created at design time are initialized with the default value. For example, if you have a Textbox Control whose text property value is "hello", this property is set. We can also dynamically create controls here.

This event only occurs in the page-level class. The user control and master page do not have this event.

The following code demonstrates how to override this method to add your custom code.
Protected override void onpreinit (eventargs E)
{
// Custom code
Base. onpreinit (E );
}
Note that themes can only be set dynamically in the preinit () event.

Special case when using the master page
First, we need to understand a very important knowledge point-the process of processing the master page is equivalent to a control in the content page.

Therefore, if a page has its associated master page, all controls on the page in the preinit () event will not be initialized. However, you can directly access these controls only after the init () event starts. Why?

This is because all the controls on the Content Page are included in "contentplaceholder", and "contentplaceholder" is actually a child control of the master page. Now the process of processing the master page is equivalent to a control in the content page. We mentioned earlier that apart from Init () and unload () all events are triggered from the outermost to the innermost. Although the page preinit () is the first event to be triggered, the user control and master page do not have this event. Therefore, in the page_preinit () method of the page, the master page and user control are not initialized, but after the init () event

Next let's take a look at the control hierarchy after the page_init () event

 


2. oninit ()
In this event, we can read the properties of the control (set in design mode ). However, we cannot read the value set by the user, because the value set by the user is obtained after the loadpostdata () event is triggered. However, we can get post data in this event, as shown below:
String selectedvalue = request. Form [controlid]. tostring ();
3. loadviewstate
This event is only triggered after sending a response (ispostback = true ). In this event, the runtime splits the view State from the hidden domain and loads it to all controls with view State enabled.

4. loadpostbackdata
This event is only triggered after sending back.
In this event, the ipostbackdatahandler interface control is implemented to get the value from the http post data. Note: The Textbox Control cannot obtain a value from view State, but from post data in this event. Therefore, even if view State is not enabled for some controls, you can obtain values from the http post data as long as it implements the ipostbackdatahandler interface.

Another important point is that if we have a dropdownlist control and dynamically add some options to it, runtime cannot obtain these values unless view State is enabled (even if the control inherits from the ipostbackdatahandler interface ). This is because each control in the http post data can only have one value, and all values in the post data will not be saved, except for the view State.

5. page_load
This is the most common method, and it is the first place for developers to place their code. Some new users often think that this is the first method to trigger the page class. This method is one of the culprit for obfuscation of our page lifecycle.

Note: if there are any user controls on the page, the load method of the user control will be triggered after the load method of the page class. This reason has been explained earlier that all events except Init () and unload () are triggered from the outermost to the innermost. Therefore, the load method of other controls on the page is triggered only after page_load () of the page.

6. Control event handlers
Event Processing (such as button1_click () is defined in the ASPX page. Some developers think that when a button is clicked, they will immediately start button_click (), they forgot to trigger page_load before this event is triggered.

7. prerender
If we want to change the value of a widget, this is the last chance.

8. saveviewstate
The viewstate of the control is stored in the hidden domain of the form.

9. Render
Rendering

10. Unload
This is the final cleanup operation.


Dynamic controls
Now that we know the important page lifecycle events, let's take a look at how to create and maintain the status of dynamically generated controls. Sometimes we need to dynamically generate controls, such as a previously managed hotel reservation project. The user enters the room number in a textbox, A user control is dynamically generated based on this value to display the details of the room.

Although developers can dynamically generate user controls, they cannot save the status of user controls. After I read the code, they wrote the code of the generated control to the Click Event of the button. As discussed above, button_click () is triggered after loadviewstate () and loadpostdata (), and the control value must be obtained in view State or post data.

Therefore, unless you re-create controls in the page_init () or pre_init () method (they occur before loadviewstate and loadpostdata), you can obtain the control values in the next event.

Now, if you write code to the page_init () event, you cannot get the value you entered in Textbox (which is a static control. The reason is that this is a page_init () event, and the control values are initialized as the default values during their design, instead of getting user-input values.

So there is only one way to access the user input value here, that is, to obtain the value from the post data. The Code is as follows:
Protected override void oninit (eventargs E)
{
// Obtain the user input value in textbox through post data
String selectedvalue;
If (request. Form ["txtnoofrooms"]! = NULL)
Selectedvalue = request. Form ["txtnoofrooms"]. tostring ();

// Dynamically generate the control code



Base. oninit (E );
}
Note: thanks to Mike banavige from the ASP. NET forum, I added this part with his help. If you create a dynamic control in the page_load event and add it to the placeholder or panel (to open the view State), the dynamic control will maintain its State, even if it was not created in page_init (), why?

The reason is that, once a control is added to the Control tree of the page, the trackviewstate () method tracks its status. This method is automatically triggered as long as the control is added to the Control tree. For this reason, any modification to the control (such as adding items) should be done after the dynamic control is added to the Control tree on the page, otherwise its status will be lost. See the following code.
Protected void page_load (Object sender, eventargs E)
{
// Create a dropdownlist
Dropdownlist d = new dropdownlist ();

// The trackviewstate () method will be triggered to track the status of this dropdownlist, so its status will be maintained
Placeholder1.controls. Add (d );

If (! Ispostback)
{
D. Items. Add ("test1 ");
D. Items. Add ("Test2 ");
}
}

The following code does not maintain the status of the dynamic control.
Protected void page_load (Object sender, eventargs E)
{
// Dynamically create a widget
Dropdowndropdownlist d = new dropdownlist ();
If (! Ispostback)
{
D. Items. Add ("test1 ");
D. Items. Add ("Test2 ");
}

// "Test1" and "Test2" values will be lost
Placeholder1.controls. Add (d );
}

Summary
I have explained some related events and their importance of the lifecycle of the page. At the same time, I will update this article occasionally to add tips and tips, readers are also welcome to point out the defects and suggestions for modification in this article.

It is very important to remember the order of the events of the entire lifecycle of the page, so that we can write the corresponding code at the right position according to different requirements.

 

 

The status of dynamically created controls cannot be saved in the code.

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.