Well, the above answer will work, but it is not good coding practice to pass a user control to the “parent form”. UserControls must be located in a separate project from your forms project, and your form project must reference your management project in order to get visibility for them. Suppose, for example, that you want this UserControl to be nested in another UserControl at some point. Your code no longer works without overloading the constructor. The best solution would be to use an event. I implemented the implementation using CustomEventArg. By doing this, your UserControl login can sit on anything and still work. If the functionality for changing the text of the parents is not specified, simply do not register in this event. Here is the code, hope this helps someone.
Here is the form code:
public Form1() { InitializeComponent(); loadlogin(); } private void loadlogin() { login log = new login();
Here is the UserControl "login" code (in my test solution, just user control with a button)
public partial class login : UserControl { //Declare Event with CustomArgs public event EventHandler<TextChangedEventArgs> changeParentTextWithCustomEvent; private String customEventText = "Custom Events FTW!!!"; public login() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Check to see if the event is registered... //If not then do not fire event if (changeParentTextWithCustomEvent != null) { changeParentTextWithCustomEvent(sender, new TextChangedEventArgs(customEventText)); } } }
And finally, the CustomEventArgs class:
public class TextChangedEventArgs : EventArgs { private String text;
Writing your controls in this way, without being visible to the forms, will allow your UserControls to be fully reused and not tied to any types or parents. Just define the behavior that UserControl can initiate and register when necessary. I know this is an old post, but hopefully this helps someone better write UserControls.
source share