How to call an event manually in C#?

前端 未结 6 1860
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 21:02

I have a USerControll in which i have a textbox. I use the usercontrol in my form, I want to do something when somebody presses enter on the textbox. how can I do it? if you

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 21:32

    What you describe is called event bubbling. Here's an example:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
    
    
    

    public partial class MyUserControl : UserControl
    {
     public event EventHandler UserControlTextBoxChanged;
    
     protected void TextBox1_TextChanged(object sender, EventArgs e) {
      if (UserControlTextBoxChanged != null)
       UserControlTextBoxChanged(sender, e);
     }
    }
    

    <%@ Page Language="C#" AutoEventWireup="True" Inherits="Default" CodeBehind="Default.aspx.cs" %>
    <%@ Register Src="~/MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
    
    
    

    public partial class MyPage : Page {
     protected void ucMyUserControl_UserControlTextBoxChanged(object sender, EventArgs e) {
      // sender is ucMyUserControl.TextBox1
     }
    }
    

提交回复
热议问题