Search code examples
c#listboxsender

how do i tie an event to multiple listboxes


i have a piece of code that id like to use for multiple listboxes. basically wherever the mouse is, select that index

driversListBox.SelectedIndex = driversListBox.IndexFromPoint(e.X, e.Y);

how would i write this so that i can tie this code to 2-3 listboxes and the code applies to whoever the sender is?

ive tried casting like below but no luck.

(Listbox)sender.IndexFromPoint(e.X, e.Y);

any help would be appreciated


Solution

  • First hook all the lists to the same event:

    list1.MouseMove += CheckMove;
    list2.MouseMove += CheckMove;
    //...
    listN.MouseMove += CheckMove;
    

    Then on the event handler:

    var currentList = sender as ListBox;
    //Now you can use currentList as it points to the list 
    //which fired the event.