【问题标题】:C# How to define event for dynamically created control?C#如何为动态创建的控件定义事件?
【发布时间】:2014-03-06 03:00:18
【问题描述】:

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

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]);
        }
    }
}

【问题讨论】:

    标签: c# events dynamic controls


    【解决方案1】:

    初始化按钮后,您可以向其添加 onclick 事件

    button[i].Click += new EventHandler(button_Click);
    

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

    【讨论】:

    • 感谢您的回复。如何在特定条件下取消订阅此事件处理程序?
    • button[i].Click -= new EventHandler(button_Click);
    猜你喜欢
    • 2014-10-31
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多