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?
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:
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.
If the "Delete" column is not the first column in the ObjectListView
, you will have to set
ShowImagesOnSubItems = true;
See also ObjectListView show icons.