Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 247
Daffi Avatar asked Sep 27 '12 20:09

Daffi


1 Answers

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.

like image 179
Rev Avatar answered Nov 05 '22 05:11

Rev