Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

Is it a bad idea to use the same function as event for different controls?

An example:

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

And assign this function as event function for ListView1, ListView2, ListView3:

this.ListView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListViewGeneric_DragEnter)
this.ListView2.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListViewGeneric_DragEnter)
this.ListView3.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListViewGeneric_DragEnter)

Another example:

private void ListViewGeneric_DragDrop(object sender, DragEventArgs e)
{
    ListView listView = sender as ListView;

    System.Drawing.Point cp = listView.PointToClient(new System.Drawing.Point(e.X, e.Y));
    ListViewItem dragToItem = listView.GetItemAt(cp.X, cp.Y);
    if (dragToItem != null)
    {
        int dropIndex = dragToItem.Index;
        MoveListItem(listView, listView.FocusedItem.Index, dropIndex);
    }
}

And do the same for DragDropEventHandler ?

In this case I can use sender to know which control called the function. Is it a bad idea? Is there something that will go bad, or became unpredictable, ambiguos?

Upvotes: 3

Views: 67

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283713

That's perfectly fine.

What you don't want to do is start with

if (sender == control1) { ... }
else if (sender == control2) { ... }
...

It's also important to name the handler in an appropriate way indicative of handling events for more than one control (you've done a good job of this).

Upvotes: 11

Related Questions