Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to access a control on another form in Windows Forms?
    primarykey
    data
    text
    <p>First off, this is a question about a desktop application using Windows Forms, not an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> question.</p> <p>I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...</p> <pre><code>otherForm.Controls["nameOfControl"].Visible = false; </code></pre> <p>It doesn't work the way I would expect. I end up with an exception thrown from <code>Main</code>. However, if I make the controls <code>public</code> instead of <code>private</code>, I can then access them directly, as so...</p> <pre><code>otherForm.nameOfControl.Visible = false; </code></pre> <p>But is that the best way to do it? Is making the controls <code>public</code> on the other form considered "best practice"? Is there a "better" way to access controls on another form?</p> <p><strong>Further Explanation:</strong></p> <p>This is actually a sort of follow-up to another question I asked, <em><a href="https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c">Best method for creating a “tree-view preferences dialog” type of interface in C#?</a></em>. 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.</p> <p>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.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload