【问题标题】:Add button from code从代码中添加按钮
【发布时间】:2015-09-13 15:01:28
【问题描述】:

我正在尝试使用代码向表单添加一个按钮,我在互联网上查找了它,但没有任何效果。

public void addSnake()
{
    Button btn = new Button();
    btn.Location = new Point(360, 390);
    btn.Size = new Size(10, 10);
    btn.Text = "";
    btn.Name = num + "";
    btn.Tag = this.oneD;
    btn.IsAccessible = false;
    Controls.Add(btn);
}

public Point getPoint()
{
    Button btn = (Button)Controls.Find(num + ""); 
    return this.pos; //temporary
}

它说“当前上下文中不存在名称'Controls'”。 (两种功能)

注意:函数 addSnake 和 getPoint 在我创建的类中

完整代码在这里:已删除

【问题讨论】:

  • 显示整个代码
  • 你创建的类是从System.Windows.Forms.Form继承的吗?否则,如果您没有自己声明,则没有此类属性。
  • 添加了完整代码。我是怎么做到的?
  • 试试 this.controls.add(btn) 而不是 controls.add(btn)。如果您在表单的代码隐藏文件中尝试此操作。

标签: c# .net forms winforms visual-studio


【解决方案1】:

您的类不是从System.Windows.Forms.Form 继承的。所以没有这样的属性叫做Controls

你可以做的是将表单的引用传递给SnakeB的构造函数:

public class SnakeB
{
    private System.Windows.Forms.Form parentForm;

    public SnakeB(System.Windows.Forms.Form parent)
    {
        parentForm = parent;
    }
}

并在您的方法中使用它,如下所示:

public Point getPoint()
{
    Button b = parentForm.Controls.Find(num + "") as Button;
    return b.Location;
}

public void addSnake(bool isFirst)
{
    Button b = new Button();
    // ...
    parentForm.Controls.Add(b);
}

用法:

public Form1()
{
    InitializeComponent();
    SnakeB snake = new SnakeB(this);
}

【讨论】:

    【解决方案2】:

    你需要在你的类中有表单的实例并将控件添加到该实例中

    public class SnakeB
    {
        int num;
        int oneD;
        Point pos = new Point();
        Form1 frm1 = new Form1();
    
    
    
     frm1.Controls.Add(btn);
    

    你将如何拥有表单的实例?如下所示

        public Form1()
        {
            InitializeComponent();
            SnakeB snake = new SnakeB(this);
        }
    

    在你的班级有一个类似的构造函数

    public class SnakeB
    {
        int num;
        int oneD;
        Point pos = new Point();
        Form1 frm1;
    
        public SnakeB()
        {
            this.num = 0;
            this.oneD = 2;
            //here construct the maain head button and 2 reguler ones
            addSnake(true);
            addSnake(false);
            addSnake(false);
        }
    
        public SnakeB(Form1 frm) : this()
        {
            this.frm1 = frm;
        }
    

    【讨论】:

    • 它创建了一个循环加载'Form1'一遍又一遍导致堆栈溢出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多