C# Adding controls to a form from another class

2019-04-16 03:57发布

问题:

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.

回答1:

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);
    }
}