Apologies : Exposing form controls to a class instance / object

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • LondonJP
    New Member
    • Jul 2012
    • 1

    Apologies : Exposing form controls to a class instance / object

    Hi all,

    First of all I'd like to apologise. There are many many posts about this around the net, however I just can't for the life of me get mine to work.

    Simply, I was to be able to expose myTextBox or myListBox to a child class.

    Code:
    namespace MyApp
    {
        public partial class MyNewApp : Form
        {
    		public void doSomething(string s)
    		{
    			myFormListbox.items.add(s);
    		}
     
            // Custom Class
            public static myClass myClassObject = new myClass();
            public class myClass
            {
    			private string myVar;
    
                //Constructor
                public myClass()
                {
                }
                //Destuctor
                ~myClass()
                {
                }
                //Some things
                public string getKey()
                {
                    return this.myVar;
                }
                public void setName(string sValue)
                {
                    this.myVar = sValue;
                }
    
    	    public void addToListBox(string s)
    		{
    			doSomething("test");
    		}
    
            }    
        }
    }
    Any pointers to anything obvious I'm doing wrong? I've tried using 'base' or 'form' and even tried passing the base form as a reference to the constructor.

    Thanks for any help.
    James
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    I know it is possible to make a class definition within another class (nesting), but id strongly suggest against it as it then becomes very easy to get tangled in knots. Instead define the class below the form class, here is an example that will hopefully answer some of your questions.

    Code:
    public partial class MyNewApp : Form
    {
        public string ParentVar;
        public MyClass instance1;
    
        public MyNewApp()
        {
            InitializeComponent();
            instance1 = new MyClass(this);
        }
    
    
        public void SetVar(string s)
        {
            instance1.MyVar = s;
        }
    }
    
    public class MyClass
    {
        public string MyVar;
        public Form Owner;
    
        public MyClass(Form owner)
        {
            this.Owner = owner;
        }
    
        public void SetParentVar(string s)
        {
            Owner.ParentVar = s;
        }
    }
    All the best!

    Aimee Bailey

    Comment

    Working...