简体   繁体   English

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

[英]Assigning Events to newly created controls

Hello I have this loop that creates labels to the form: 您好,我有这个循环,为表单创建标签:

  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;


        }

And I have some Events on MouseMove and MouseDown that makes the control availible for grab and drop it with mouse. 我在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;
        }
    }

My question is: Is there any way I can assing those events to newly created labels? 我的问题是:有什么办法可以将这些事件关联到新创建的标签?

Thanks in advance for your time. 在此先感谢您的时间。

Try this: 尝试这个:

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

Jay 周杰伦

You need to wire and un-wire your events. 您需要连线和取消连线事件。 Handlers that are hanging around is a source of memory leaks. 徘徊的处理程序是内存泄漏的根源。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM