C#如何为动态创建的控件定义事件?

时间:2014-02-08 17:10:58

标签: c# events dynamic controls

我编写了一个动态创建按钮的代码。代码运行良好,并在单击按钮时创建控件。现在接下来的任务是,我想为这些动态创建的控件定义click事件。我怎样才能做到这一点 ?下面是代码,请修改此代码并粘贴回复,以便我能够轻松理解。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    // create controls dynamically on form
    int n = 4;
    private void btnDisplay_Click_1(object sender, EventArgs e)
    {
        Button[] button = new Button[n];

        int previousButtonPositionY;
        int previousButtonHeight;

        for (int i = 0; i < n; i++)
        {
            button[i] = new Button();
            button[i].Name = "btnButton" + i;
            button[i].Text = "btnButton" + i;
            if (i > 0)
            {
                previousButtonPositionY = button[i - 1].Location.Y;
                previousButtonHeight = button[i - 1].Height;
            }
            else 
            {
                previousButtonPositionY = 50;
                previousButtonHeight = 0;
            }

            button[i].Location = new Point(0, previousButtonPositionY + previousButtonHeight);
        }

        for (int i = 0; i < n; i++)
        {
            panel1.Controls.Add(button[i]);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

初始化按钮后,您可以使用

添加onclick事件
button[i].Click += new EventHandler(button_Click);

更多信息:http://msdn.microsoft.com/en-us/library/ms743596%28v=vs.110%29.aspx