Why does Form1.Controls give CS120 error?

Viewed 25

i want to dynamically update textbox via button. I've created this for loop:

public void add_players_Click(object sender, EventArgs e) 
        {
            if (enter_name_space.Text == "")
            {
                messagebox_1 hide = new messagebox_1();
                hide.Show();
            }
            else
            {
                for (int i = 0; i < 2;)
                {
                    TextBox textBox = new TextBox();
                    textBox.Text = "Hi";
                    textBox.Name = "textBox" + i.ToString();
                    Form1.Controls.Add(enter_name_space);
                    textBox.Location = new Point(0, 0);
                }
            }
        }

but then error "CS0120: An object reference is required for the nonstatic field, method, or property" occurs on "Form1.Controls". Why is that? How do I fix it?

1 Answers

You need to create an instance of the object. "object" being Form1.

In your Form1:

public static Form1 instance;
public Form1()
{
    InitializeComponent();
    instance = this;
}

Now, whenever you want to access a control in Form1 from any other form or class, you need to do:

Form1.instance...

So in your Form2 (or whatever):

public void add_players_Click(object sender, EventArgs e) 
{
    if (enter_name_space.Text == "")
    {
        messagebox_1 hide = new messagebox_1();
        hide.Show();
    }
    else
    {
        for (int i = 0; i < 2;)
        {
            TextBox textBox = new TextBox();
            textBox.Text = "Hi";
            textBox.Name = "textBox" + i.ToString();
            textBox.Location = new Point(0, 0);
            Form1.instance.Controls.Add(textBox);
        }
    }
}
Related