This article mainly introduces the simplest custom controls in the ASP.net, as well as the core code examples, the need for friends can refer to the following
Asp. NET user controls are generally useful for generating relatively static content, so there is no BUILTIN event support. This article discusses how the user control returns events.
Assuming that the user control (USERCONTROL.ASCX) contains a button control Abutton, you want the page that contains the user control to receive events when you press the Abutton button. To do this, the chick shooter is handled separately in the user control and the page code.
Processing in UserControl.ascx.cs:
1. Define public event delegates, such as ClickEventHandler;
2. Declare an event in the UserControl class, such as Click;
3. Define the method that raises the event in the UserControl class, such as the OnClick () method;
4. Invoke the method that raises the event in the related method of the UserControl class, such as calling OnClick () in Button_Click ().
The core code is indicated as follows:
The 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);
}
}
The processing in the page CS file containing UserControl:
1. InitializeComponent () to increase the event handler, using the FindControl method to find UserControl;
2. Define the event-handling method in which UserControl events, such as usercontrol_clicked (), are handled.
The core code is indicated as follows:
The 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, the event mechanism is added by means of a manual programming approach: Adding code that is automatically generated by the general control IDE. By the way, C # 's event mechanism obeserver pattern, in addition to the UI can also be used for business layer, can effectively reduce the coupling between objects, like UserControl, there is no need to know the Page object containing it!