如何在运行时在 WinForm 中添加按钮? [英] How to add Buttons in WinForm in Runtime?

查看:28
本文介绍了如何在运行时在 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 )

            }
        }

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

I dont want to create a form at run time but add the dynamically created buttons to my Current Winform i.e: GUIWevDav

谢谢

推荐答案

你的代码的问题是你试图在 GUIWevbDavControls.Add() 方法> 这是您的表单类型,您无法在类型上获取 Control.Add,它不是静态方法.它仅适用于实例.

Problem in your code is that you're trying to call Controls.Add() method on GUIWevbDav which is the type of your form and you can't get Control.Add on a type, it's not a static method. It only works on instances.

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

}

这篇关于如何在运行时在 WinForm 中添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆