Search code examples
c#listboxcontextmenustrip

Deleting a Specific Item from multiple listboxes


I'm trying to delete a specific item from multiple listBoxes. I've created a ContextMenuStrip which contains a Delete Button.

I can delete the listbox item by clicking a right click on the mouse and pressing the delete button on the ContextMenuStrip. But I would be happy to know if I can do it on multiple Listboxes.

This it the writing button code:

listBox1.Items.Add("Hello");

this it the delete button code:

listBox1.Items.Remove(listBox1.SelectedItem);
listBox1.Refresh();

Solution

  • Before showing the contextMenu, you can set the tag property to the listbox you clicked:

    contextMenuStrip1.Tag = listBox1;
    contextMenuStrip1.Show();
    

    Then, on the Opened event, cast to a ListBox and remove the item:

    var lb = ((ListBox)contextMenuStrip1.Tag);
    lb.Items.Remove(lb.SelectedItem);