How to add controls on the ASP. NET page as required by the project.
In fact, the bloggers have all provided answers. This article only provides some tests and conclusions.
Add controls on ASP. NET pagesThe key to the problem is that all the control initialization operations should be completed when the page is loaded. The dynamic loading process delays the loading process after the event is triggered. Therefore, after the page is sent back, because there will be a new page loading process, it is clear that the Dynamically Loaded control does not exist at this time, but the user expected answer is to display the loaded information. At this time, if possible, we 'd better re-load the control and bind the data during the loading process.
According to the thinking of ordinary people
Public void addtextboxs ()
{
Tablerow TR = new tablerow ();
Tablecell TC1 = new tablecell ();
Textbox T = new Textbox ();
T. ID = "TB" + table1.rows. count;
Tc1.controls. Add (t );
Tablecell TC2 = new tablecell ();
Dropdownlist DPL = new dropdownlist ();
DPL. ID = "DPL" + table1.rows. count;
For (INT I = 0; I <10; I ++) DPL. Items. Add (I. tostring ());
Tc2.controls. Add (DPL );
Tr. cells. Add (TC1 );
Tr. cells. Add (TC2 );
Table1.rows. Add (TR );
}
Then add a click event to a button.
Protected void button#click (Object sender, eventargs E)
{
Addtextboxs ();
}
ProgramTest. You can generate related controls on the page.
The problem is that if you press another button, you will find that the dynamic control you added disappears, not to mention how to pull the value?
According to the search answer, the reason is that after each button, the page is re-posted, and the related control must be re-added, so add in formload event
Protected void page_load (Object sender, eventargs E)
{
If (viewstate ["count"]! = NULL)
{
For (INT I = 0; I <convert. toint16 (viewstate ["count"]); I ++)
Addtextboxs ();
}
}
Protected void button#click (Object sender, eventargs E)
{
Addtextboxs ();
If (viewstate ["count"] = NULL) addbutton ();
Viewstate ["count"] = convert. toint16 (viewstate ["count"]) + 1;
}