Common events? [closed]

1

Good evening, I would like to associate a common event for all the label_DragOver and label_DragDrop ... such thing would be possible?

    string _currLabel = string.Empty;
    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.Items.Add("lol1");
        listBox1.Items.Add("lol2");
        listBox1.Items.Add("lol3");
        listBox1.Items.Add("lol4");
        listBox1.Items.Add("lol5");
    }

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if(listBox1.SelectedItem!=null)
        { 
            DragDropEffects _effect = DoDragDrop(listBox1.SelectedItem, 
                                                  DragDropEffects.All);
        }         
    }

    private void ChangeLabelName(Label c)
    {
       c.Text = _selectedItem(); 

    }

    private string _selectedItem()
    {
        return listBox1.GetItemText(listBox1.SelectedItem);
    }

    private void label1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.All;
    }

    private void label1_DragDrop(object sender, DragEventArgs e)
    {
        Label s = (Label)sender;
        ChangeLabelName(s);         
    }
    
asked by anonymous 23.11.2017 / 01:16

1 answer

4

If I understand correctly, you want to associate the same event with N different labels, right? If so, I believe the code below will give you at least one light.

Example:

void InitializeLabelsEvent() 
{
    //vai pegar todos os controls tipo label dentro do control
    var labels = this.Controls.OfType<Label>();
    foreach(var label in labels) 
    {
        //ira associar em cada label o respectivo evento
        //nt: cuidado, pois se ele associar mais de uma vez o evento
        //ele será chamado quantas vezes for associado, portanto associe 
        //apenas uma vez
        label.DragOver += new DragEventHandler(DragOverEvent);

        //mas se por alguma razão você precisar chamar o metódo novamente
        //remova o evento do control e depois adicione novamente
        //exemplo:               
        label.DragOver -= new DragEventHandler(DragOverEvent);//remove
        label.DragOver += new DragEventHandler(DragOverEvent);//add
    }

}

//evento dragover
void DragOverEvent(object sender, DragEventArgs e) 
{
    e.Effect = DragDropEffects.All;
    //codigo aqui
}

The same thing would be for DragDrop.

    
23.11.2017 / 02:54