Search code examples
c#winformslistviewobjectlistview

ObjectListView Not Showing Selection Color For Selected Item


I have an ObjectListView which is essentially a wrapper around the standard .NET ListView. My problem is that I cannot figure out the correct sequence of method calls to add a new object to the control, scroll the control to ensure that the object is visible, and select the object. Below, is my code to achieve this. Everything works but, for some reason the background color for the selected item/object does not show up until I click on or re-size one of the columns. I'm not sure if the control is not being focused or what.

// objectListViewItems is of type BrightIdeasSoftware.ObjectListViewItems
objectListViewItems.AddObject(e.InsertedItem);
objectListViewItems.Refresh();
objectListViewItems.Focus();
objectListViewItems.EnsureModelVisible(e.InsertedItem);
objectListViewItems.SelectedObject = e.InsertedItem;
objectListViewItems.Focus();

The code below updates an item in the ObjectListView and works just fine. Not sure what I'm doing wrong above...

objectListViewItems.RefreshObject(itemToEdit);
objectListViewItems.Focus();
objectListViewItems.SelectObject(itemToEdit);

Solution

  • This should work like you proposed (I did this on several occasions). However, calling Refresh() and the second Focus() is unnecessary. Also I would rather use SelectObject() than the SelectedObject property.

    Like this:

    objectListView.AddObject(newItem);
    objectListView.Focus();
    objectListView.EnsureModelVisible(newItem);
    objectListView.SelectObject(newItem);
    

    Also, make sure that there is no code executed afterwards, that may cause another control to get the focus.

    To narrow down what's happening, you could try setting

    objectListView.HideSelection = false;
    

    As for the normal ListView, this ensures that the current selection stays visible (but "grayed" out), even if the control loses focus.

    Please post the complete OLV configuration (from InitializeComponent()) if you used the designer. Maybe there is some weird constellation causing this.