简体   繁体   中英

user control and raising events from controls placed in user control

So I would like to know what is wrong with the following code, especially from a theoretical point of view.

I have a user control in which I've added a text box. When I click in the text box I would like the Mouse clicked event raised in the user control. To my mind, the solution should be: Create an event handler for the mouse click event in the text box. in this event handler, raise the mouse click event for the user control.

so this is what i have:

    private void txtLog_MouseClick(object sender, MouseEventArgs e)
    {
        this.OnMouseClick(e);
    }

i have tried it and it doesn't work, why is this?

PS I would really like to know why this is wrong! A correct solution is great, but I'm really trying to understand where I'm going wrong here. Thank :-)

Well, you could just click on your textbox in design mode and in the property window in events tab add the click event. or if you want to do it in runtime you can do it like this:

 textbox.Click += Txt_Click;

    private static void Txt_Click(object sender, EventArgs e)
    {
       // do your thing
    }

or even shorter:

textbox.Click += (s,e) =>
{
    //do your thing
};

you should do these three steps

  • declare an MouseClick delegation method for textbox
  • assign method to textbox
  • add this delegation to the this (form) OnMouseClick event [on user control constructor]

Step1:

    private void textBox1_MouseClick(object sender, MouseEventArgs e)
    {

    }

Step2:

this.textBox1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseClick);

Step3:

    public myUserControl()
    {
        InitializeComponent();

        this.MouseClick += new MouseEventHandler(textBox1_MouseClick);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM