代码之家  ›  专栏  ›  技术社区  ›  Simsons

如何在运行时在WinForm中添加按钮?

  •  3
  • Simsons  · 技术社区  · 15 年前

    我有以下代码:

    public GUIWevbDav()
    {
        InitializeComponent();
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            //My XML Loading and other Code Here
    
            //Trying to add Buttons here
            if (DisplayNameNodes.Count > 0)
            {
                for (int i = 0; i < DisplayNameNodes.Count; i++)
                {
                    Button folderButton = new Button();
                    folderButton.Width = 150;
                    folderButton.Height = 70;
                    folderButton.ForeColor = Color.Black;
                    folderButton.Text = DisplayNameNodes[i].InnerText;
    
                    Now trying to do  GUIWevbDav.Controls.Add
                    (unable to get GUIWevbDav.Controls method )
    
                }
            }
    

    我不想在运行时创建一个窗体,而是将动态创建的按钮添加到我当前的Winform中,即:GUIWevDav

    3 回复  |  直到 15 年前
        1
  •  6
  •   this. __curious_geek    15 年前

    代码中的问题是您试图调用 Controls.Add() 上的方法 GUIWevbDav 这是您窗体的类型,您无法获得控件。添加一个类型,它不是静态方法。它只适用于实例。

    for (int i = 0; i < DisplayNameNodes.Count; i++) 
    { 
    
        Button folderButton = new Button(); 
        folderButton.Width = 150; 
        folderButton.Height = 70; 
        folderButton.ForeColor = Color.Black; 
        folderButton.Text = DisplayNameNodes[i].InnerText; 
    
        //This will work and add button to your Form.
        this.Controls.Add(folderButton );
    
        //you can't get Control.Add on a type, it's not a static method. It only works on instances.
        //GUIWevbDav.Controls.Add
    
    }
    
        2
  •  7
  •   Petar Minchev    15 年前

    只是使用 this.Controls.Add(folderButton) . this 这是你的表格。

        3
  •  3
  •   Incognito    15 年前

    你需要和我一起工作 Control.Controls Form Class Members 你可以看到 Controls 财产。

    像这样使用:

    this.Controls.Add(folderButton);  // "this" is your form class object.