An example of a button with an onclick event:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Web. UI;
Using system. componentmodel;
Namespace componentcontrol
{
[Defaultproperty ("text")]
[Toolboxdata ("<{0}: mybutton runat = Server> </{0}: mybutton>")]
Public class ctrl4: control, ipostbackeventhandler
{
Public event eventhandler click; // defines the event. eventhandler is the system delegate name.
Ipostbackeventhandler member # region ipostbackeventhandler Member
// This method is used to register an event
Public void raisepostbackevent (string eventargument)
{
If (Click! = NULL)
{
Click (this, eventargs. Empty); // implement the delegate Method
}
}
# Endregion
Public String text // set the attribute text value
{
Get {return viewstate ["text"] = NULL? "Button": viewstate ["text"]. tostring ();}
Set {viewstate ["text"] = value ;}
}
Protected override void render (htmltextwriter writer)
{
Writer. addattrimit (htmltextwriterattribute. type, "Submit ");
Writer. addattribute (htmltextwriterattribute. Name, this. uniqueid); // similar to the following code, this triggers a server event. The attribute must be name and cannot be ID.
// Writer. addattrireference (htmltextwriterattribute. onclick, page. getpostbackeventreference (this ));
Writer. addattriter( htmltextwriterattribute. Value, text );
Writer. renderbegintag (htmltextwritertag. Input );
Writer. renderendtag ();
// Writer. Write ("<input type = submit name =" + this. uniqueid + "value = 'click'/> ");
}
}
}
Another optimized event implementation
The eventhandlerlist class provides a simple delegate list to add and delete delegates. Next, let's look at the changed code,
Addhandler has two parameter event objects and added delegates. In The onclick event, the delegate must be converted to the eventhandler type.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Web. UI;
Namespace componentcontrol
{
Public class ctrl5: control, ipostbackeventhandler
{
// Declare the click event Delegate
Private Static readonly object OBJ = new object ();
Public Virtual Event eventhandler click
{
Add {
Events. addhandler (OBJ, value );
}
Remove
{
Events. removehandler (OBJ, value );
}
}
Protected override void render (htmltextwriter writer)
{
Writer. Write ("<input type = submit name =" + this. uniqueid + "value = button/> ");
}
Ipostbackeventhandler member # region ipostbackeventhandler Member
Public void raisepostbackevent (string eventargument)
{
Eventhandler child = (eventhandler) events [OBJ];
If (child! = NULL)
Child (this, eventargs. Empty );
}
# Endregion
}
}