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

我有以下代码:

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

谢谢

你的代码中的问题是你试图在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 } 

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

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

像这样用它:

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