简体   繁体   English

C#将控件添加到另一个类的表单中

[英]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 每次我创建一个新的Player实例时,我都想做以下代码

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 eg textbox1.text = "Test" . 我似乎无法与form1做任何事情,例如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? 有谁知道我怎么可以访问+通过类添加控件到我的form1

Thank you for your time. 感谢您的时间。

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: 听起来你想要将Player类中的控件添加到你正在调用的表单中,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM