How to add an event to a UserControl in C#?

后端 未结 6 2243
一向
一向 2020-11-27 05:04

I have a UserControl which contains 3 labels. I want to add an event for it, which occurs when the text of one of the labels changed.
I am using Visual Studio 2010

6条回答
  •  抹茶落季
    2020-11-27 05:16

    There is a very simple way to do that!

    On the UserControl Form :

    1. change properties to public to access everywhere

    on the main form , where you are using UserControl:

    .5: in the using region add using userControl1=UserControl.userControl1

    1.Add 'Laod' event to your UserControl :

    this.userControl1.Load += new System.EventHandler(this.userControl1_Load);
    

    2.In the userControl1_Load :

    private void userControl1_Load(object sender, EventArgs e)
    {
         (sender as UserControl1).label1.TextChanged += label1_TextChanged; 
         //add a 'TextChanged' event to the label1 of UserControl1 
         OR use direct cast:
         ((UserControl1) sender).label1.TextChanged += label1_TextChanged;
    
    }
    

    3.In th label1_TextChanged:

     private void label1_TextChanged(object sender, EventArgs e)
     {
         //do whatever you want
     }
    

提交回复
热议问题