Search code examples
c#eventsgroupingmouseevent

C# assign an event to a "group" of controls?


I have a big numbers of labels custom controls let's say 100. I would like to give them an MouseHover event. I could do something like:

private void label_custom1_MouseHover(object sender, EventArgs e)
        {
            TextBox.Text = label_custom1.backcolor.ToString();
        }

But then I would need to do that 100 times. Since I have 100 of them. Is there a way to do that only once? I guess I should probably declare the function in my custom_label class but so far I couldn't make it work. Any Idea how to proceed?


Solution

  • Firstly, create a common event, we receive the Label posted here.

    private void Common_MouseHover(object sender, EventArgs e)
    {
        TextBox.Text = (sender as Label).BackColor.ToString();
    }
    

    Give the common event to all Labels on the form. Here I assume Label names start with label, for example label1, label2, label3 ...

    private void SetEventAllLabels()
    {
        var labels = Controls.OfType<Label>().Where(x => x.Name.StartsWith("label"));
        foreach (var label in labels)
        {
            label.MouseHover += Common_MouseHover;
        }
    }
    

    Call the SetEventAllLabels () method in the Load method of the form.

    private void Form1_Load(object sender, EventArgs e)
    {
        SetEventAllLabels();
    }