给一个用户控件加自定义的事件

Posted on 2006-09-06 23:39  Alvin Ye 叶冬开  阅读(1149)  评论(0编辑  收藏  举报
/*Title:给一个用户控件加自定义的事件
 *Author: Alvin
 *Date: Sep 6,2006
 *Description: 给一个用户控件加自定义的事件 并回传一个参数
 *Environment: WinXP sp2,Vs2005 pro,.netFramework 2.0
 *KeyWord: 给一个用户控件加自定义的事件 并回传一个参数 UserControl
 */
Step 1
 
新建一个类:
CustomerEventArgs.cs
 
public class CustomerEventArgs : EventArgs
{
  private int m_SelectId;
 
  public int SelectId
  {
    get { return m_SelectId; }
    set { m_SelectId = value; }
  }
  public CustomerEventArgs(int p_SelectId)
  {
    this.SelectId = p_SelectId;
  }
}
 
Step 2
新建一个用户控件 Add new Web User Control
并在控件上放两个 Button  如下
WebUserControl.ascx
 
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Button ID="Button2" runat="server" Text="Button" />
 
Step 3
打开WebUserControl.ascx.cs
3.1
 定义一个代理类型
 public event CustomerEventHandler customerEvent;
3.2
 定义事件
 public event CustomerEventHandler customerEvent;
3.3
定义方法 OncustomerEvent来处理事件
  public virtual void OncustomerEvent(CustomerEventArgs e)
  {
    if (customerEvent != null)
    {
      customerEvent(this, e);
    }
  }
 
Step 4
给两个button 加上事件
 
WebUserControl.ascx
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
 
WebUserControl.ascx.cs
  protected void Button1_Click(object sender, EventArgs e)
  {
    OncustomerEvent(new CustomerEventArgs(1));
  }
  protected void Button2_Click(object sender, EventArgs e)
  {
    OncustomerEvent(new CustomerEventArgs(2));
  }
Step 5
 打开 default.aspx 引用并以上控件 并写好事件
 
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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl ID="WebUserControl1" runat="server" OncustomerEvent="CustomerEvent" />
   
    </div>
    </form>
</body>
</html>
 
default.aspx.cs
 
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
  protected void CustomerEvent(object o, CustomerEventArgs e)
  {
    Response.Write(e.SelectId.ToString());
 
  }
}

Copyright © 2024 Alvin Ye 叶冬开
Powered by .NET 9.0 on Kubernetes