How can I call the controls of other class?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thin July
    New Member
    • Feb 2011
    • 1

    How can I call the controls of other class?

    How can I call the controls of other class? they are same level within only one namespace..
    but I can't ...So what should I do?
    by namespace declaration or by taking inheritance? or how?
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    You can only call what's publicly exposed by a class. The controls are usually defined privately so you'll need to open up some access. While you certainly could make the control itself public, it's considered a best practice to only expose functionality you choose, thus preventing people from messing with your classes in unintended ways.

    The most basic example here would be a public property... lets say you had a form with a button on it and you wanted to change the text on that button, you might do the following:

    Code:
    public class MainForm : Form
    {
      private SubForm m_subForm = new SubForm();
    
      ...
    
      public void SomeMethod()
      {
        m_subForm.ButtonText = "NO";
      }
    
      ...
    
    }
    
    public class SubForm : Form
    {
      private Button m_button = new Button();
    
      ...
    
      public SubForm()
      {
        m_button.Text = "OK";
      }
    
      // ButtonText property
      public string ButtonText
      {
        get { return m_button.Text; }
        set { m_button.Text = value; }
      }
    
      ...
    
    }
    That's the simplest way... for more detailed information one of our experts, Curtis Rutland, has done an excellent writeup, you can read it here:

    Comment

    Working...