I have a program that dynamically creates controls when it starts, it works just fine when the code to do this is in the class of the actual form. I tried moving the code to a separate class and found that I could not use Controls.Add(). How can I add controls to the Form from a separate class? This is what I have so far:
TextBox txtbx = new TextBox();
txtbx.Text = "asd" + x.ToString();
txtbx.Name = "txtbx" + x.ToString();
txtbx.Location = new Point(10, (20 * x));
txtbx.Height = 20;
txtbx.Width = 50;
Controls.Add(txtbx);
Error 1 The name ‘Controls’ does not exist in the current context
Controlsis actually a property exposed by theControlclass (and therefore theFormclass, since it inherits fromControl) , and it represents a collection of all the controls that have been added to that particular instance of the form class.That is why you can’t use it from another class, because you don’t have a reference to the
Formobject to which you’re trying to add the controls in the other class. That’s what it means by “does not exist in the current context”.You need to pass the instance of the form to which you want to add the controls as a parameter to the method in the class that will add the controls:
But you should probably reconsider the design of your application if you’re forced into a position like this. You really shouldn’t be adding controls to a form from a separate class because that increases the amount of coupling between your UI and ancillary classes, which you should strive to minimize to every extent possible. In general, most of the time that you find something is particularly difficult to do, that should send up a red flag that you might be trying to do it the wrong way.