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

时间:2010-07-02 06:08:32

标签: c# winforms

我有以下代码:

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 )

            }
        }

我不想在运行时创建表单,而是将动态创建的按钮添加到Current Winform,即:GUIWevDav

由于

3 个答案:

答案 0 :(得分:7)

只需使用this.Controls.Add(folderButton)即可。 this是您的表格。

答案 1 :(得分:6)

您的代码中的问题是,您尝试在Controls.Add()上调用GUIWevbDav方法,这是您表单的类型,并且您无法获取某个类型的Control.Add,它不是静态方法。它只适用于实例。

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 :(得分:3)

您需要使用Control.Controls属性。 在Form Class Members中,您可以看到Controls属性。

像这样使用:

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