(Forum Q & A Drop) User Control Dynamic Load Postback after PostBack

xiaoxiao2021-03-05  24

Many netizens dynamically add user controls in the button Click event disappeared after the page returns or the button event in the user control cannot trigger. The following is a solution: (1) Add a user control: WebUserControl1.ascx Add a button : Public system.web.ui.webControls.button UCB; Text is "User Control button" (the button will be used to use this button in Page, so set to public) Click Events for Button: Response.Write (I.TOString ()); i ; Static Int i = 0 in the class; Click on the button to see a click, the count increase 1 (2) Add a page to place a PlaceHolder, two buttons Add a single-load user control: private void adduc () {WebUserControl1 uc = (WebUserControl1) Page.loadControl ("WebuserControl1.ascx"); uc.id = "uc"; this.PlaceHolder1.controls.add (UC);} Add Click event for the first button: private void button1_click (object sender, system.eventargs e) {if (viewState ["adduc"] == null) {adduc (); viewstate ["adduc"] = 1;}} We add a flag bit in the view state, indicating whether or not to click the button to load the user control, of course, if the button has been loaded, it is not necessary to repeat it. The key is to load user controls when it is page.ispostback (because if you don't do it, the user control disappears when the return is ") IF (page.ispostback) {if (ViewState [" adduc "]! = NULL) {adduc ();}} You can click on button1 test, is it loaded with user controls? At the same time, click the button in the user control can also trigger its events.

转载请注明原文地址:https://www.9cbs.com/read-38159.html

New Post(0)