给WEB用户控件添加事件

在创建某个用户控件时,我使用了TextBox控件,我想用户控件也有TextChanged这样的事件,怎么实现呢?下面提供了一种方法。

阅读本部分内容需要具备【委托(delegate)和事件(event)】的相关知识 。实际上,代码非常简单。

1、创建用户控件

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserTextBox.ascx.cs" Inherits="UserTextBox" %>
<asp:TextBox ID="txtUserTextBox" runat="server" 
    ontextchanged
="txtUserTextBox_TextChanged"></asp:TextBox>

using System;

public partial class UserTextBox : System.Web.UI.UserControl
{
    
#region private fields
    
private string _Text;
    
#endregion

    
public delegate void TextChangedHandler(object sender, TextChangedEventArgs e);
    
public event TextChangedHandler TextChanged;

    
public void OnTextChaged(TextChangedEventArgs e)
    {
        
if (TextChanged != null)
        {
            TextChanged(
this, e);
        }
    }
    
//在这里触发事件
    protected void txtUserTextBox_TextChanged(object sender, EventArgs e)
    {
        OnTextChaged(
new TextChangedEventArgs(txtUserTextBox.Text));
    }
    
/// <summary>
    
/// 事件数据类
    
/// </summary>
    public class TextChangedEventArgs : EventArgs
    {
        
public readonly string Text;
        
public TextChangedEventArgs(string Text)
        {
            
this.Text = Text;
        }
    }

    
#region Properties
    
public bool AutoPostBack
    {
        
get
        {
            
return txtUserTextBox.AutoPostBack;
        }
        
set
        {
            txtUserTextBox.AutoPostBack 
= value;
        }
    }
    
public string Text
    {
        
get { return _Text; }
        
set { _Text = value; }
    }
    
#endregion
}

2、使用ASP.NET窗体测试

注意:事件不能在属性窗口点击“闪电”符号那里添加,而是在窗体类中写代码添加的,这里是重写了基类Page中的OnInit方法。

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register src="UserTextBox.ascx" tagname="UserTextBox" 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>无标题页</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
        
<uc1:UserTextBox ID="UserTextBox1" runat="server" 
            AutoPostBack
="True"/>
    
    
</div>
    
</form>
</body>
</html>

 

using System;

public partial class _Default : System.Web.UI.Page 
{

    
void UserTextBox1_TextChanged(object sender, UserTextBox.TextChangedEventArgs e)
    {
        Response.Write(e.Text);
    }

    
protected override void OnInit(EventArgs e)
    {
        
this.UserTextBox1.TextChanged += new UserTextBox.TextChangedHandler(UserTextBox1_TextChanged);
        
base.OnInit(e);
    }
}

转载于:https://www.cnblogs.com/Ferry/archive/2009/07/09/1520006.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值