简体   繁体   中英

Creating Event Handlers

So I create dynamic labels in a loop, labels for a list of file folders in a directory.

i want, when you click on the label, the files within the label will display in a listbox. but i cannot get my event handler working, is it necessary to give my label a name as shown, i feel like i need the name for the event, but if the name is dynamic, the event name needs to be too and i cannot do that. also, i will need access to the labels properties within the event, so thats why i created an overloaded method, but regardless, clicking on the label does not do either of my event handlers. please advise, i'd appreciate it. here is whats in my loop and my event handlers

                    string str = lstMovieFolders[i];
                    Label lbl = new Label();
                    lbl.Name = "lbl" + str;
                    lbl.Location = new Point(25, intStartPoint);
                    lbl.Text = str;
                    lbl.Size = new Size(x, y);
                    lbl.Click += new EventHandler(lbl_Click);
                    grp.Controls.Add(lbl);
                    intStartPoint += 30;

   public static void lbl_Click(object sender, EventArgs e)
    {
        MessageBox.Show("HELLOS");
    }
   public static void lbl_Click(object sender, EventArgs e, Label lbl)
    {
        MessageBox.Show("HELLO");
    }

You can use sender parameter to get the current Label that triggers the event.You do not need an overload

public static void lbl_Click(object sender, EventArgs e)
{
    var label = sender as Label;
    if(label != null)
    {
        string text = label.Text;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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