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

感情迁移 提交于 2019-12-01 18:02:37

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.

huoxudong125

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

ShowImagesOnSubItems = true;

See also ObjectListView show icons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!