views:

2843

answers:

2

Hi i have a UserControl which contains the textbox within, 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 publically exposed UserControl in Winforms with C#.

+1  A: 

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!

Galilyou
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
+10  A: 

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; }
    }
}
Matt Hamilton
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
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
Is there anything else to make this work? somehow the event handler added declaratively does not work
Nassign