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

Question :

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

Answer :

First off, this is a question about a desktop application using Windows Forms, not an  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?

Read More  VS 2008 – Objects disappearing?

Further Explanation:

This is actually a sort of follow-up to another question I asked,  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.)

Read More  Ant build scripts, antcall, dependencies, etc


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.

That’s the answer Best way to access a control on another form in Windows Forms?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

Read More  Import Namespace System.Query

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you