Reputation: 10213
I'm trying to create a function that adds usercontrols to my mainform. I want this function to be available from the usercontrols themselves as well, so I'm making it static.
My problem is that when it's static I can't use this.Controls.Add(ucontrol);
, I tried to change it to ActiveForm.Controls.Add(ucontrol);
but then ActiveForm is NULL and has no Controls property (throws an exception).
UPDATE #1: I ended up doing something like this inside the usercontrol:
MainForm ref_to_mainform_to_gain_access_to_functions = (MainForm)Parent;
ref_to_mainform_to_gain_access_to_functions.DisplayControl(ucontrol);
maybe it's even better, but I still assume it's possible to have access to the mainform from a static method?
UPDATE #2:
Application.OpenForms["FormName"]
worked from static method.
I still try to find out if that usercontrol entire purpose is serve as a menu with buttons that shows other usercontrols onclick, is it still a 'design-crime' to call a function on mainform (a function that shows usercontrols) from a user control? (like I did in 'update #1')
Upvotes: 0
Views: 666
Reputation: 1020
By adding controls from a user control to its parent you are breaking the separation of concerns principle and you are tightly coupling both controls/forms. As suggested by Hans Passant you should use events. Please refer to: best practices to call methods in the parent form and access gui elements in parent form in c#
Upvotes: 1