繁体   English   中英

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

[英]How to add Buttons in WinForm in Runtime?

我有以下代码:

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

谢谢

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

你的代码中的问题是你试图在GUIWevbDav上调用Controls.Add()方法,这是你的表单的类型,你不能在类型上获得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

}

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

像这样使用它:

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

暂无
暂无

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

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