Franz Payer
Franz Payer

Reputation: 4137

Using control from a separate class in C#

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

Upvotes: 0

Views: 2026

Answers (2)

Cody Gray
Cody Gray

Reputation: 244712

Controls is actually a property exposed by the Control class (and therefore the Form class, since it inherits from Control) , 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 Form object 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:

public void AddControls(Form frm)
{
    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;
    frm.Controls.Add(txtbx);
}

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.

Upvotes: 4

Josh
Josh

Reputation: 69242

You need a reference to the form at least. In your Program.cs class, you can store a reference to the main form like:

public class Program {

    public static Form MainForm;

    public static void Main() {
        ...
        MainForm = new Form1();
        Application.Run(MainForm);

    }

}

Then to add controls to the main form you could do:

Program.MainForm.Controls.Add(txtbx);

Of course that introduces a whole other issue of tightly coupling your classes this way but from the question it sounds like you're new to Windows Forms or .NET so there's no sense in going over that issue for now.

Upvotes: 1

Related Questions