将MouseHover事件分配给新创建的Control

时间:2013-10-07 14:30:52

标签: c# .net controls

这是新的控件添加代码部分:

        for (int i = 0; i < 1; i++)
        {
            var newLabel = new Label();
            newLabel.Location = new Point(x, y);
            newLabel.Size = new System.Drawing.Size(25, 25);

            newLabel.Name = "lbl" + realpocsed.ToString();

            if (value2== "Value2")
            {
                newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
                newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
            }
            if (value== "Value1")
            {
                newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseHover);

            }

            panel1.Controls.Add(newLabel);

MouseHover事件如下所示:

        private void MyControl_MouseHover(object sender, MouseEventArgs e)
    {
        ToolTip ToolTip1 = new ToolTip();
        ToolTip1.ShowAlways = true;
        ToolTip1.Show("t", X); // X should be name of the newly created label
    }

请问是否有办法分配新创建的名称"lbl" + realpocsed.ToString()而不是X

感谢您的时间。

3 个答案:

答案 0 :(得分:2)

您正在为MouseHover代码分配MouseDown事件,但不确定是否需要。

它应该是这样的:

newLabel.MouseHover += MyControl_MouseHover;

对于你的X,你必须施放发件人:

ToolTip1.Show("Hover Message Here", (Label)sender);

答案 1 :(得分:1)

您无法通过在字符串中创建其名称来访问任何对象。这样做的简单方法是传递对象引用:

ToolTip1.Show("t", (sender as Label));

答案 2 :(得分:0)

内部for

newLabel.MouseHover += delegate (object sender, EventArgs e)
{
    ToolTip ToolTip1 = new ToolTip();
    ToolTip1.ShowAlways = true;
    ToolTip1.Show("t", newLabel);
};

更新

if (value == "Value1")
{
    newLabel.MouseHover += delegate (object sender, EventArgs e)
    {
        ToolTip ToolTip1 = new ToolTip();
        ToolTip1.ShowAlways = true;
        ToolTip1.Show("t", newLabel);
    };
}