ObjectListView - Delete a row by clicking on a designated column with fixed content/text
Asked Answered
I

2

5

I have a simple question which i am not able to solve myself.

I have an ObjectListView filled with some of my objects. But in addition to that I want to have another column, with a default text "Delete". On clicking that column, the selected Row should be deleted. How do I do that?

Inappropriate answered 27/9, 2012 at 20:20 Comment(0)
F
13

You can achieve this by making the desired row editable and use the CellEditActivation event. Initialize your OLV and "delete-column" as follows:

// fire cell edit event on single click
objectListView1.CellEditActivation = ObjectListView.CellEditActivateMode.SingleClick;
objectListView1.CellEditStarting += ObjectListView1OnCellEditStarting;

// enable cell edit and always set cell text to "Delete"
deleteColumn.IsEditable = true;
deleteColumn.AspectGetter = delegate {
    return "Delete";
};

Then you can remove the row in the CellEditStarting handler as soon as the column is clicked:

private void ObjectListView1OnCellEditStarting(object sender, CellEditEventArgs e) {
    // special cell edit handling for our delete-row
    if (e.Column == deleteColumn) {
        e.Cancel = true;        // we don't want to edit anything
        objectListView1.RemoveObject(e.RowObject); // remove object
    }
}

To improve on this, you can display an image in addition to the text.

// assign an ImageList containing at least one image to SmallImageList
objectListView1.SmallImageList = imageList1;

// always display image from index 0 as default image for deleteColumn
deleteColumn.ImageGetter = delegate {
    return 0;
};

Result:

enter image description here

If you don't want to display any text next to the image you can use

deleteColumn.AspectToStringConverter = delegate {
    return String.Empty;
}; 

You could also set the Aspect to an empty string, but consider this as "best practice". By still returning an aspect, sorting and grouping will still work.

Filamentous answered 2/11, 2012 at 8:31 Comment(0)
A
0

If the "Delete" column is not the first column in the ObjectListView, you will have to set

ShowImagesOnSubItems = true;

See also ObjectListView show icons.

Acquit answered 14/8, 2013 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.