Simple custom controls in ASP. NET and asp.net controls
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.
Processing in UserControl. ascx. 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 the related methods of the UserControl class. For example, call OnClick () in Button_Click ().
The core code is as follows:
Copy codeThe 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 the event processing method, and process the UserControl event in this method, such as UserControl_Clicked ().
The core code is as follows:
Copy codeThe 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!