将事件分配给新创建的控件

时间:2013-09-30 21:21:40

标签: c# .net winforms

您好我有这个循环为表单创建标签:

  private Label newLabel = new Label();
    private int txtBoxStartPosition = 300;
    private int txtBoxStartPositionV = 25;

    private void button1_Click(object sender, EventArgs e)
    {
        int txt = Int32.Parse(textBox1.Text);
        for (int i = 0; i < txt; i++)
        {
            newLabel = new Label();
            newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV);
            newLabel.Size = new System.Drawing.Size(25, 25);
            newLabel.Text = i.ToString();
            newLabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            newLabel.ForeColor = Color.Red;
            newLabel.Font = new Font(newLabel.Font.FontFamily.Name, 10);
            newLabel.Font = new Font(newLabel.Font, FontStyle.Bold);
            newLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;  

            this.Controls.Add(newLabel);
            txtBoxStartPosition -= 35;


        }

我在MouseMove和MouseDown上有一些事件可以让控件可以抓取并用鼠标放下它。

        private Point MouseDownLocation;

    private void MyControl_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void MyControl_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            label1.Left = e.X + label1.Left - MouseDownLocation.X;
            label1.Top = e.Y + label1.Top - MouseDownLocation.Y;
        }
    }

我的问题是:我有什么方法可以将这些事件分配给新创建的标签吗?

提前感谢您的时间。

2 个答案:

答案 0 :(得分:3)

试试这个:

newLabel.MouseMove += MyControl_MouseMove;
newLabel.MouseDown += MyControl_MouseDown;

答案 1 :(得分:3)

您需要连接和取消连接事件。闲逛的处理程序是内存泄漏的来源。

List<Label> myLabels = new List<Label>(txt);

for (int i = 0; i < txt; i++)
{
    newLabel = new Label();
    newLabel.MouseMove += MyControl_MouseMove;
    newLabel.MouseDown += MyControl_MouseDown;
    myLabels.Add(newLabel);
.......

// Later in Dispose
foreach (var lbl in myLabels)
{
     lbl -= MyControl_MouseMove;
     lbl -= MyControl_MouseDown;
}
myLabels.Clear();