Best way to access a control on another form in Windows Forms?

Dylan Bennett picture Dylan Bennett · Aug 12, 2008 · Viewed 172.1k times · Source

First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question.

I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...

otherForm.Controls["nameOfControl"].Visible = false;

It 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.)

Answer

Jon Limjap picture Jon Limjap · Aug 12, 2008

Instead of making the control public, you can create a property that controls its visibility:

public bool ControlIsVisible
{
     get { return control.Visible; }
     set { control.Visible = value; }
}

This creates a proper accessor to that control that won't expose the control's whole set of properties.