Thursday, April 21, 2011

expose and raise event of a child control in a usercontrol in c#

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#.

From stackoverflow
  • 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!

    Anirudh Goel : thanks, i had done similar thing as of now. Was looking for an elegant solution which was provided above.Thanks for your help.+1
  • 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; }
        }
    }
    
    Anirudh Goel : 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!
    Thomas Levesque : 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
    Nassign : Is there anything else to make this work? somehow the event handler added declaratively does not work

0 comments:

Post a Comment