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
2009-06-03 05:24:36
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
2009-06-03 05:48:13
+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
2009-06-03 05:28:39
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
2009-06-03 05:47:36
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
2009-07-03 22:11:10
Is there anything else to make this work? somehow the event handler added declaratively does not work
Nassign
2010-04-16 01:48:44