页面中的一些操作需在用户控件的按钮(以下简称按钮)点击时激发,这就需要在页面中监听按钮点击事件,一种实现方式在用户控件中添加自定义事件,在页面中订阅事件,按钮点击点激发自定义事件,代码如下:
1). 用户控件WebUserControl
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class WebUserControl : System.Web.UI.UserControl
{
//委托
public delegate void MyClickEventHandler();
//事件
public event MyClickEventHandler MyClick;
//方法
public void OnMyClick()
{
if (MyClick != null)
MyClick();
}
/// <summary>
/// 按钮点击事件处理程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
OnMyClick();
}
}
2). .NET页面
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!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>在页面中监听用户控件的按钮点击事件-Mzwu.Com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label> </div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1.MyClick += new WebUserControl.MyClickEventHandler(ToDo);
}
protected void ToDo()
{
Label1.Text += DateTime.Now.ToString() + ": WebUserControl1控件中的Button1被你点坏了!<br/>";
}
}
效果图: