Search code examples
c#eventscontextmenuobjectlistview

ObjectListView get object with contextmenu


Hy!

I would like to create an ObjectListView, where you can delete items with a ContextMenu.

So basicly I used to delete it by getting OLV.SelectedIndex, and then deleting from the list OLV is based on, and re-setting the OLV objects. Then I realized, if I sort the OLV, then delete an item, it deletes another item, since the selected item index does not equals the index in the list.

With OLV CellRightClick event I can get the object behind the clicked item (e.Model),but I dont know how to pass it to the ContextMenu click event handler.

Subjects is a List.

private void subjectListView_CellRightClick(object sender, BrightIdeasSoftware.CellRightClickEventArgs e)
{
if (subjectsListView.SelectedIndex != -1)
{
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Delete", new EventHandler(DeleteItem));
subjectsListView.ContextMenu = cm;
}
}

void DeleteItem(object sender, EventArgs e)
{
//get the Subject object, which was clicked on
Subjects.RemoveAt(subjectsListView.SelectedIndex);
subjectsListView.SetObjects(Subjects);
}

So basically I want to get the object (not the index) when the ContextMenus "Delete" item is clicked. Also, I feel like there is an easier way to do this.

Thanks for the answer.


Solution

  • I would just assign an appropriate ContextMenuStrip from the designer to the ObjectListView.ContextMenuStrip property and then handle the click of the corresponding "Delete" click like this:

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e) {
            if (objectListView1.SelectedObject != null) {
                objectListView1.RemoveObject(objectListView1.SelectedObject);
            }
        }
    

    Or is there a requirement I am missing from your question?