Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get double click listbox selected

Tags:

c#

events

I'm having trouble with some C#.. I have a listbox, when I double click an entry I want to return the string of whatever I double clicked..

How do I do this?

like image 490
Andy Avatar asked Mar 22 '23 18:03

Andy


1 Answers

I assume you're using WinForms.

If you're working with single selection then it's pretty easy: on the double click handler (please check how to do it with Google or see later) check SelectedItem property. Double clicked item is selected too.

void OnMouseDoubleClick(object sender, MouseEventArgs e)
{
    var list = (ListBox)sender;

    // This is your selected item
    object item = list.SelectedItem;
}

If you're working with multi-selection you need to be more check which item has been clicked because it may be last selected one, you can use IndexFromPoint() method like this:

void OnMouseDoubleClick(object sender, MouseEventArgs e)
{
    var list = (ListBox)sender;

    int itemIndex = list.IndexFromPoint(e.Location);
    if (itemIndex != -1)
    {
        // This is your double clicked item
        object item = list.Items[itemIndex];
    }
}

EDIT How to add an event handler? Google is your friend here but in short you have to select the control, open properties page, select events then double click the input box near MouseDoubleClick event. Designer will add code for you anyway you should first start with that basics...

like image 154
Adriano Repetti Avatar answered Mar 24 '23 10:03

Adriano Repetti