简体   繁体   中英

C# ListBox or DataGrid double click SELECTED item

I have a problem with returning selected item from listbox or DataGrid. The problem is, I specifically want user to double click the chosen item, not anywhere else on the control (as is with DoubleClick event). Currently I have this:

private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem == null) return;
        System.Console.WriteLine(listBox1.SelectedItem.ToString()); //console for testing
    }

While it works, I don't like the fact that you can click once on an item and then double click anywhere on blank space of the control and it returns the previously selected item. Is there any easy way to change it?

You should get item index from the location where double click event occur:

int index = listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
  System.Console.WriteLine(listBox1.SelectedItem.ToString()); //console for testing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM