Home > database >  Double click on listbox item – C#
Double click on listbox item – C#

Time:11-04

I have some items in my listbox, when I double click on one of these items I want the MessageBox to appear with the information of the item I double-clicked. E.g., I click an item "Item 1" and the MessageBox is shown with the "Item 1" text. Here is the solution I have for now, but it returns the index of the item, not the actual item:

private void empLbx_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = this.empLbx.IndexFromPoint(e.Location);
            if (index != System.Windows.Forms.ListBox.NoMatches) 
            {
                MessageBox.Show(index.ToString());
            }
        }

CodePudding user response:

Try this:

private void empLbx_MouseDoubleClick(object sender, MouseEventArgs e)
{
    int index = this.empLbx.IndexFromPoint(e.Location);
    if (index != System.Windows.Forms.ListBox.NoMatches) 
    {
       MessageBox.Show(empLbx.SelectedItem.ToString());
    }
}

CodePudding user response:

this is your form there and not the ListBox, your listbox is the variable sender. so change your code like:

int index = ((ListBox)sender).SelectedIndex;
if(index != -1) 
    MessageBox.Show(index.ToString());

If no item is selected, or listbox is empty index will be -1 so if(index != -1) handles both.

  • Related