Here's how to create a user control with an event:
The standard web space has events to interact with, as does the user control.
To create a user control with events is simple and requires only three steps:
1. Define an open (public) event delegate, such as ClickEventHandler
2. Define the method that raises the event in the user control class, such as the OnClick method
3. In the method that raises the event to determine whether the event is empty, if not NULL, you can write the event out of the code.
Here we go step-by-step to achieve
1. Create a user control file--linkclick.ascx.
2. Drag the LinkButton control from the Toolbox.
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
--><%@ control language= "C #" autoeventwireup= "true" codebehind= "LinkClick.ascx.cs" inherits= "Sample9_2". Uc.linkclick "%>
<asp:linkbutton id= "LinkButton1" runat= "Server" > click me </asp:LinkButton>
3. Define the delegate for the Click event in the LinkClick.ascx.cs post code
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
-->public event EventHandler Myclickeventhandler;
4. The Click event code for the Add LinkButton control is as follows:
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
-->protected void LinkButton1_Click (object sender, EventArgs e)
{
if (Myclickeventhandler!= null) {
Myclickeventhandler (this, eventargs.empty);
}
}
5. In Default.aspx, drag the user control that you just made
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
--><uc1:linkclick id= "LinkClick1" runat= "Server"/>
6. In the Toolbox, drag the lable control, we will do when clicking on the user Control LinkButton, let lable display content.
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> <asp:label id= "Label1" runat= "Server" ></asp:Label>
7. Add the user control event handle to the user control.
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> <uc1:linkclick id= "LinkClick1" runat= "Server" onmyclickeventhandler= "Linkclick1_onclick"/>
8. Open the file, Default.aspx.cs, add the event inside the definition code of the function Linkclick1_onclick
The code is as follows (when the user clicks the control LinkClick, the event is raised and the corresponding text is displayed in the Lablel control).
Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/
-->protected void Linkclick1_onclick (object sender, EventArgs e)
{
This. Label1.Text = "click me";
}
It would be nice to have a user control with an event. Run and try.