Search code examples
c#winformslabelflowlayoutpanel

Double Click doesnt work on Label


I'm trying to open a form after a label is double clicked. My Code:

else if (e.Clicks == 2)
{
    foreach (var control in myFLP.Controls)
    {
        if(control is Label)
        {
            var Id = mylabel.Name.ToString();
            int personID;

            if (!String.IsNullOrWhiteSpace(Id) && int.TryParse(Id, out personID))
            {
                Form frm = new Form(_controller, personID);
                frm.ShowDialog();
                frm.Dispose();
            }
            else 
            {
                Form2 frm2 = new Form2();
                frm2.ShowDialog();
                frm2.Dispose();
                Console.WriteLine("Hello");
            }
        }
    }
}

When i double click on the label nothing happens? So i tried calling Form frm = new Form(); without passing any parameters. The form opened after the double click, but kept opening for every label in the myFLP?

Edit 1: I have added an ELSE. I think my condition in incorrect.


Solution

  • You probably subscribed to event Control.Click. You should subscribe to event Control.DoubleClick.

    If you are using Visual Studio designer, select the label you want to react on double-click; go to properties (-enter), Select the flash to see all events, and look for DoubleClick in the Action category.

    In function InitializeComponent() (see the constructor of your form) You'll see something similar to:

    this.label1.DoubleClick += new System.EventHandler(this.label1_DoubleClick);
    

    the event handling function:

    private void label1_DoubleClick(object sender, EventArgs e)
    {
        // sender is the label that received the double click:
        Debug.Assert(Object.ReferenceEquals(sender, this.label1));
    
        Label doubleClickedLabel = (Label)Sender;
        var Id = doubleClickedLabel.Text;
        int personID;
        if (!String.IsNullOrWhiteSpace(Id) && int.TryParse(Id, out personID))
        {   // open form. Note the use of the using statement
            using (Form frm = new Form(_controller, personID)
            {
                frm.ShowDialog();
            }
        }
        else 
        {
            using (Form2 frm2 = new Form2())
            {
                frm2.ShowDialog();
            }
        }
    }