Ralt
Ralt

Reputation: 2216

C# Adding controls to a form from another class

Every time I create a new instance of Player I want to do the following code

private void button1_Click(object sender, EventArgs e)
{
   Player Player1 = new Player();
}

Player class
{
    public Player()
    {
        Form1.AddControls(someControl)
    }
}

I can't seem to do anything to do with form1 e.g. textbox1.text = "Test". I assume this is a scope issue but I can't find an answer on the internet. Does anyone know how I can access + add controls to my form1 through a class?

Thank you for your time.

Upvotes: 1

Views: 8235

Answers (1)

mservidio
mservidio

Reputation: 13057

It's not entirely clear what you're trying to do. It sounds like you want to add controls from the Player class into the form that you're calling from like this:

public class Form1 : Form
{
    public void SomeMethod()
    {
        Player player1 = new Player(this);
    }
}

public class Player()
{
    public Player(Form form)
    {
        Textbox tb = new Textbox();
        form.Controls.Add(tb);
    }
}

Upvotes: 4

Related Questions