26

Hi. I have a UserControl which contains a textbox. I wanted to access the textchanged event of the textbox but in the event properties of the usercontrol I don't see the events for the textbox. How can I expose and handle particular events of the child controls from the publicly exposed UserControl in Winforms with C#.

Joachim Prinsloo
  • 618
  • 3
  • 12
  • 31
Anirudh Goel
  • 4,571
  • 19
  • 79
  • 109

2 Answers2

42

You can surface a new event and pass any subscriptions straight through to the control, if you like:

public class UserControl1 : UserControl 
{
    // private Button saveButton;

    public event EventHandler SaveButtonClick
    {
        add { saveButton.Click += value; }
        remove { saveButton.Click -= value; }
    }
}
Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • Awesome thing! I did something similar, by explicitly adding an event handler as i had exposed the child control publically through the usercontrol. Your suggestion is the neater way of it! Thanks! – Anirudh Goel Jun 03 '09 at 05:47
  • 11
    Despite its elegance, this solution has a major drawback : the `sender` argument passed to the handler will be the Button, not the UserControl... This makes it impossible to use the same handler for several instances of the control – Thomas Levesque Jul 03 '09 at 22:11
  • Is there anything else to make this work? somehow the event handler added declaratively does not work – Nap Apr 16 '10 at 01:48
  • If you get the button not the UserControl as the argument, possibly you could get the parent then to tell which parent usercontrol the event came from...I don't really know but just a guess...maybe you have to code the user control correctly to do this. – Dean Hiller Jun 08 '12 at 14:24
1

Expose the entire TextBox as a public property in user control and subscribe to it's events the way you desire.
Example:

class myUserControl: UserControl { 
private TextBox _myText;
public TextBox MyText { get {return _myText; } }

}

After doing this you can subscribe on any of its events like so:

theUserControl.MyText.WhatEverEvent += ... 

Hope this helps!

Ahmed
  • 11,063
  • 16
  • 55
  • 67
  • thanks, i had done similar thing as of now. Was looking for an elegant solution which was provided above.Thanks for your help.+1 – Anirudh Goel Jun 03 '09 at 05:48