First off, this is a question about a desktop app using Windows Forms, not an ASP.Net question.
I need to interact with controls on other forms. Trying to access the controls by using, for example, the following...
otherForm.Controls["nameOfControl"].Visible = false;
...doesn't work the way I would expect. I end up with an exception thrown from Main
. However, if I make the controls public
instead of private
, I can then access them directly, as so...
otherForm.nameOfControl.Visible = false;
But is that the best way to do it? Is making the controls public
on the other form considered "best practice"? Is there a "better" way to access controls on another form?
Further Explanation:
This is actually a sort of follow-up to another question I asked: Best method for creating a “tree-view preferences dialog” type of interface in C#? The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.
Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)
Final Answer (so far):
Note to Jeff Atwood: Can we please "accept" multiple answers? So it seems the best practice would be to either only expose the actual property that's needed, or to handle it through raising events in the form whose controls I need to manipulate. Hard to say which will be best in my case. I will have to develop the application further before I see which will be easier to manage. Many thanks, though, for the speedy replies.