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

后端 未结 2 2024
北海茫月
北海茫月 2021-01-19 01:16

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

相关标签:
2条回答
  • 2021-01-19 01:50

    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.

    0 讨论(0)
  • 2021-01-19 01:59

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

    ShowImagesOnSubItems = true;
    

    See also ObjectListView show icons.

    0 讨论(0)
提交回复
热议问题