1)用户控件前台代码TestWebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestWebUserControl.ascx.cs" Inherits="WebApplication74.TestWebUserControl" %>
<table>
<tr>
<td>test button</td>
<td><asp:LinkButton ID="TestLinkButton" runat="server"
οnclick="TestLinkButton_Click">TestLinkButton</asp:LinkButton></td>
</tr>
</table>
2)用户控件后台代码TestWebUserControl.ascx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication74
{
public partial class TestWebUserControl : System.Web.UI.UserControl
{
/// <summary>
/// 定义委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void MyDelegate(object sender, EventArgs e);
/// <summary>
/// 定义事件
/// </summary>
public event MyDelegate myEvent;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TestLinkButton_Click(object sender, EventArgs e)
{
//将自定义事件绑定到控件事件上
if (myEvent != null)
{
myEvent(sender, e);
}
}
}
}
3)web页面前台代码Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication74.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
4)web页面后台代码Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication74
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TestWebUserControl testWebUserControl = (TestWebUserControl)Page.LoadControl("~/TestWebUserControl.ascx");
testWebUserControl.myEvent += new TestWebUserControl.MyDelegate(testWebUserControl_myEvent);
Panel1.Controls.Add(testWebUserControl);
}
void testWebUserControl_myEvent(object sender, EventArgs e)
{
Label1.Text = "Test Success.";
}
}
}