ASP. NET user controls are generally used to generate relatively static content, so there is no builtin event support. This topic describes how a user control returns an event. Assume that the user control (UserControl. ascx) contains the button control AButton. If you want to press the AButton button, the page containing the user control can receive the event. To this end, the chicken shooter processes the user control and page Code respectively.
UserControl. ascx. processing in cs: 1. define public event delegation, such as ClickEventHandler; 2. declare events in the UserControl class, such as Click; 3. define the method for triggering the event in the UserControl class, such as The OnClick () method; 4. call the method that triggers the event in related methods of the UserControl class, for example, call OnClick () in Button_Click ().
The core code is as follows: public delegate void ClickEventHandler (object sender, EventArgs e); public class MyUserControl: System. web. UI. userControl {protected System. web. UI. webControls. button AButton; public event ClickEventHandler Click; protected void OnClick (EventArgs e) {if (Click! = Null) Click (this, e);} private void AButton_Click (object sender, System. EventArgs e) {this. OnClick (e );}}
Processing in the cs file of the page containing UserControl: 1. added an event handler in InitializeComponent () and used the FindControl method to locate UserControl; 2. define an event processing method to process the UserControl event in this method, such as UserControl_Clicked (). The core code is as follows: private void InitializeComponent () {this. load + = new System. eventHandler (this. page_Load); MyUserControl uc = this. findControl ("myUserControlID") as MyUserControl; uc. click + = new ClickEventHandler (this. userControl_Clicked);} private void UserControl_Clicked (object sender, System. eventArgs e) {// UserControl_Clicked event hanlder}
To sum up, we add the event mechanism to the code automatically generated by the general control IDE by means of manual programming. By the way, the C # event mechanism implements the Obeserver pattern. In addition to the UI, it can also be used at the business layer to effectively reduce the coupling between objects, like UserControl, you don't need to know who the page object contains it!