C#Windows窗体(在运行时添加新控件)[复制]

时间:2022-02-10 15:01:38

This question already has an answer here:

这个问题在这里已有答案:

I have started new windows form apllication and I want to add some Control instance when I press any button.(I want program to add two more button if I press AddButton).

我已经启动了新的Windows窗体应用程序,我想在按任何按钮时添加一些控件实例。(如果我按下AddButton,我希望程序再添加两个按钮)。

1 个解决方案

#1


3  

You need at least some x,y cordinates to place it, then you can check the button's properties and change it however you want.

您至少需要一些x,y坐标来放置它,然后您可以检查按钮的属性并根据需要进行更改。

private void createButton(string name, int x, int y)
{
    // Create button
    Button btn = new Button();

    // Set button name
    btn.Name = name;

    // Set location
    btn.Location = new Point(x, y);

    //Hook our button up to our generic button handler
    btn.Click += new EventHandler(btn_Click);

    // Add it to the main panel
    // panel1 is your application name
    panel1.Controls.Add(
}

void btn_Click(object sender, EventArgs e)
{
    MessageBox.Show("This is the handler of the button that we created");
}

Then in the main button that creates the buttons you can call the button like this:

然后在创建按钮的主按钮中,您可以像这样调用按钮:

createButon("some name", 5,5);

#1


3  

You need at least some x,y cordinates to place it, then you can check the button's properties and change it however you want.

您至少需要一些x,y坐标来放置它,然后您可以检查按钮的属性并根据需要进行更改。

private void createButton(string name, int x, int y)
{
    // Create button
    Button btn = new Button();

    // Set button name
    btn.Name = name;

    // Set location
    btn.Location = new Point(x, y);

    //Hook our button up to our generic button handler
    btn.Click += new EventHandler(btn_Click);

    // Add it to the main panel
    // panel1 is your application name
    panel1.Controls.Add(
}

void btn_Click(object sender, EventArgs e)
{
    MessageBox.Show("This is the handler of the button that we created");
}

Then in the main button that creates the buttons you can call the button like this:

然后在创建按钮的主按钮中,您可以像这样调用按钮:

createButon("some name", 5,5);