Handling double click events on ListBox items in C#

Hans Espen picture Hans Espen · Aug 8, 2010 · Viewed 14.7k times · Source

I am trying to do something when double clicking an item in a ListBox. I have found this code for doing that

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        int index = this.listBox1.IndexFromPoint(e.Location);
        if (index != System.Windows.Forms.ListBox.NoMatches)
        {
            MessageBox.Show(index.ToString());
            //do your stuff here
        }
    }

However, when i click on an item, the event isn't fired. The event is fired if i click in the ListBox below all the items.

I set the DataSource property of the ListBox to IList<MyObject>.

Any ideas?

Answer

26071986 picture 26071986 · Aug 9, 2010

Tried creating a form with a ListBox with MouseDown and DoubleClick events. As far as I can see, the only situation, when DoubleClick won't fire, is if inside the MouseDown you call the MessageBox.Show(...). In other cases it works fine.

And one more thing, I don't know for sure, if it is important, but anyway. Of course, you can get the index of the item like this:

int index = this.listBox1.IndexFromPoint(e.Location);

But this way is fine as well:

if (listBox1.SelectedItem != null)
    ...